package x509
import (
)
type pkcs8 struct {
Version int
Algo pkix.AlgorithmIdentifier
PrivateKey []byte
}
func ( []byte) ( interface{}, error) {
var pkcs8
if , := asn1.Unmarshal(, &); != nil {
if , := asn1.Unmarshal(, &ecPrivateKey{}); == nil {
return nil, errors.New("x509: failed to parse private key (use ParseECPrivateKey instead for this key format)")
}
if , := asn1.Unmarshal(, &pkcs1PrivateKey{}); == nil {
return nil, errors.New("x509: failed to parse private key (use ParsePKCS1PrivateKey instead for this key format)")
}
return nil,
}
switch {
case .Algo.Algorithm.Equal(oidPublicKeyRSA):
, = ParsePKCS1PrivateKey(.PrivateKey)
if != nil {
return nil, errors.New("x509: failed to parse RSA private key embedded in PKCS#8: " + .Error())
}
return , nil
case .Algo.Algorithm.Equal(oidPublicKeyECDSA):
:= .Algo.Parameters.FullBytes
:= new(asn1.ObjectIdentifier)
if , := asn1.Unmarshal(, ); != nil {
= nil
}
, = parseECPrivateKey(, .PrivateKey)
if != nil {
return nil, errors.New("x509: failed to parse EC private key embedded in PKCS#8: " + .Error())
}
return , nil
case .Algo.Algorithm.Equal(oidPublicKeyEd25519):
if := len(.Algo.Parameters.FullBytes); != 0 {
return nil, errors.New("x509: invalid Ed25519 private key parameters")
}
var []byte
if , := asn1.Unmarshal(.PrivateKey, &); != nil {
return nil, fmt.Errorf("x509: invalid Ed25519 private key: %v", )
}
if := len(); != ed25519.SeedSize {
return nil, fmt.Errorf("x509: invalid Ed25519 private key length: %d", )
}
return ed25519.NewKeyFromSeed(), nil
default:
return nil, fmt.Errorf("x509: PKCS#8 wrapping contained private key with unknown algorithm: %v", .Algo.Algorithm)
}
}
func ( interface{}) ([]byte, error) {
var pkcs8
switch k := .(type) {
case *rsa.PrivateKey:
.Algo = pkix.AlgorithmIdentifier{
Algorithm: oidPublicKeyRSA,
Parameters: asn1.NullRawValue,
}
.PrivateKey = MarshalPKCS1PrivateKey()
case *ecdsa.PrivateKey:
, := oidFromNamedCurve(.Curve)
if ! {
return nil, errors.New("x509: unknown curve while marshaling to PKCS#8")
}
, := asn1.Marshal()
if != nil {
return nil, errors.New("x509: failed to marshal curve OID: " + .Error())
}
.Algo = pkix.AlgorithmIdentifier{
Algorithm: oidPublicKeyECDSA,
Parameters: asn1.RawValue{
FullBytes: ,
},
}
if .PrivateKey, = marshalECPrivateKeyWithOID(, nil); != nil {
return nil, errors.New("x509: failed to marshal EC private key while building PKCS#8: " + .Error())
}
case ed25519.PrivateKey:
.Algo = pkix.AlgorithmIdentifier{
Algorithm: oidPublicKeyEd25519,
}
, := asn1.Marshal(.Seed())
if != nil {
return nil, fmt.Errorf("x509: failed to marshal private key: %v", )
}
.PrivateKey =
default:
return nil, fmt.Errorf("x509: unknown key type while marshaling PKCS#8: %T", )
}
return asn1.Marshal()
}