rsa/pkg/inspect/private_key.go

113 lines
2.5 KiB
Go
Raw Normal View History

2023-03-01 21:28:48 +00:00
package inspect
import (
"crypto/rsa"
"crypto/x509"
"errors"
)
// PKCS1PrivateKeyInfo attempts to parse a DER-form PKCS#1-encoded private RSA
// key, and returns information about it.
func PKCS1PrivateKeyInfo(loc string, der []byte) Info {
key, err := x509.ParsePKCS1PrivateKey(der)
if err != nil {
return &BadInfo{
Typ: TypePrivateKey,
Loc: loc,
Underlying: err,
}
}
return PrivateKeyInfo(loc, key)
}
// PKCS1PrivateKeyInfo attempts to parse a DER-form PKCS#8-encoded private RSA
// key, and returns information about it.
func PKCS8PrivateKeyInfo(loc string, der []byte) Info {
key, err := x509.ParsePKCS8PrivateKey(der)
if err != nil {
return &BadInfo{
Typ: TypePrivateKey,
Loc: loc,
Underlying: err,
}
}
rsakey, ok := key.(*rsa.PrivateKey)
if !ok {
return &BadInfo{
Typ: TypePrivateKey,
Underlying: errors.New("PKCS#8 private key ytpe is not RSA"),
}
}
return PrivateKeyInfo(loc, rsakey)
}
// PrivateKeyInfo returns structured information about the given RSA private key.
func PrivateKeyInfo(loc string, key *rsa.PrivateKey) *PrivateKey {
pl := make([]int, len(key.Primes))
for i, n := range key.Primes {
pl[i] = n.BitLen()
}
return &PrivateKey{
Loc: loc,
Primes: len(key.Primes),
PrimeLens: pl,
Public: PublicKeyInfo(loc, &key.PublicKey),
}
}
// PrivateKey holds structured information about an RSA private key. It
// implements Info.
type PrivateKey struct {
// Loc is the location the key was encountered.
Loc string
// Primes is the number of primes, ≥ 2.
Primes int
// PrimeLens holds the bit length of each prime.
PrimeLens []int
// Public holds information about the public portion of the key.
Public *PublicKey
}
// Type indicates this is a private key.
func (priv *PrivateKey) Type() Type {
return TypePrivateKey
}
// Location returns the location data stored by PrivateKeyInfo.
func (priv *PrivateKey) Location() string {
return priv.Loc
}
// Info returns structured information about the prvate key.
func (priv *PrivateKey) Info() []Section {
return []Section{
priv.PrivateKeyInfoSection(),
priv.Public.PublicKeyInfoSection(),
}
}
// PrivateKeyInfoSection returns the RSA private key specific information
// section.
func (priv *PrivateKey) PrivateKeyInfoSection() Section {
return Section{
Title: "RSA private key",
Fields: []Field{
Field{
Key: "Primes",
Value: priv.Primes,
},
Field{
Key: "Prime lengths",
Value: priv.PrimeLens,
},
},
}
}