github.com/zmap/zcrypto@v0.0.0-20240512203510-0fef58d9a9db/ct/x509/pkcs8.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package x509
     6  
     7  import (
     8  	// START CT CHANGES
     9  	"github.com/zmap/zcrypto/ct/asn1"
    10  	"github.com/zmap/zcrypto/ct/x509/pkix"
    11  	// END CT CHANGES
    12  	"errors"
    13  	"fmt"
    14  )
    15  
    16  // pkcs8 reflects an ASN.1, PKCS#8 PrivateKey. See
    17  // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn
    18  // and RFC5208.
    19  type pkcs8 struct {
    20  	Version    int
    21  	Algo       pkix.AlgorithmIdentifier
    22  	PrivateKey []byte
    23  	// optional attributes omitted.
    24  }
    25  
    26  // ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See
    27  // http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208.
    28  func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) {
    29  	var privKey pkcs8
    30  	if _, err := asn1.Unmarshal(der, &privKey); err != nil {
    31  		return nil, err
    32  	}
    33  	switch {
    34  	case privKey.Algo.Algorithm.Equal(oidPublicKeyRSA):
    35  		key, err = ParsePKCS1PrivateKey(privKey.PrivateKey)
    36  		if err != nil {
    37  			return nil, errors.New("x509: failed to parse RSA private key embedded in PKCS#8: " + err.Error())
    38  		}
    39  		return key, nil
    40  
    41  	case privKey.Algo.Algorithm.Equal(oidPublicKeyECDSA):
    42  		bytes := privKey.Algo.Parameters.FullBytes
    43  		namedCurveOID := new(asn1.ObjectIdentifier)
    44  		if _, err := asn1.Unmarshal(bytes, namedCurveOID); err != nil {
    45  			namedCurveOID = nil
    46  		}
    47  		key, err = parseECPrivateKey(namedCurveOID, privKey.PrivateKey)
    48  		if err != nil {
    49  			return nil, errors.New("x509: failed to parse EC private key embedded in PKCS#8: " + err.Error())
    50  		}
    51  		return key, nil
    52  
    53  	default:
    54  		return nil, fmt.Errorf("x509: PKCS#8 wrapping contained private key with unknown algorithm: %v", privKey.Algo.Algorithm)
    55  	}
    56  }