gitee.com/lh-her-team/common@v1.5.1/crypto/x509/sec1.go (about)

     1  // Copyright 2012 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  	"crypto/ecdsa"
     9  	"crypto/elliptic"
    10  	"encoding/asn1"
    11  	"errors"
    12  	"fmt"
    13  	"math/big"
    14  )
    15  
    16  const ecPrivKeyVersion = 1
    17  
    18  // ecPrivateKey reflects an ASN.1 Elliptic Curve Private Key Structure.
    19  // References:
    20  //   RFC 5915
    21  //   SEC1 - http://www.secg.org/sec1-v2.pdf
    22  // Per RFC 5915 the NamedCurveOID is marked as ASN.1 OPTIONAL, however in
    23  // most cases it is not.
    24  type ecPrivateKey struct {
    25  	Version       int
    26  	PrivateKey    []byte
    27  	NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"`
    28  	PublicKey     asn1.BitString        `asn1:"optional,explicit,tag:1"`
    29  }
    30  
    31  // ParseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
    32  func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error) {
    33  	return parseECPrivateKey(nil, der)
    34  }
    35  
    36  // MarshalECPrivateKey marshals an EC private key into ASN.1, DER format.
    37  func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error) {
    38  	oid, ok := oidFromNamedCurve(key.Curve)
    39  	if !ok {
    40  		return nil, errors.New("x509: unknown elliptic curve")
    41  	}
    42  	return marshalECPrivateKeyWithOID(key, oid)
    43  }
    44  
    45  // marshalECPrivateKey marshals an EC private key into ASN.1, DER format and
    46  // sets the curve ID to the given OID, or omits it if OID is nil.
    47  func marshalECPrivateKeyWithOID(key *ecdsa.PrivateKey, oid asn1.ObjectIdentifier) ([]byte, error) {
    48  	privateKeyBytes := key.D.Bytes()
    49  	paddedPrivateKey := make([]byte, (key.Curve.Params().N.BitLen()+7)/8)
    50  	copy(paddedPrivateKey[len(paddedPrivateKey)-len(privateKeyBytes):], privateKeyBytes)
    51  	return asn1.Marshal(ecPrivateKey{
    52  		Version:       1,
    53  		PrivateKey:    paddedPrivateKey,
    54  		NamedCurveOID: oid,
    55  		PublicKey:     asn1.BitString{Bytes: elliptic.Marshal(key.Curve, key.X, key.Y)},
    56  	})
    57  }
    58  
    59  // parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
    60  // The OID for the named curve may be provided from another source (such as
    61  // the PKCS8 container) - if it is provided then use this instead of the OID
    62  // that may exist in the EC private key structure.
    63  func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {
    64  	var privKey ecPrivateKey
    65  	if _, err := asn1.Unmarshal(der, &privKey); err != nil {
    66  		return nil, errors.New("x509: failed to parse EC private key: " + err.Error())
    67  	}
    68  	if privKey.Version != ecPrivKeyVersion {
    69  		return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version)
    70  	}
    71  	var curve elliptic.Curve
    72  	if namedCurveOID != nil {
    73  		curve = namedCurveFromOID(*namedCurveOID)
    74  	} else {
    75  		curve = namedCurveFromOID(privKey.NamedCurveOID)
    76  	}
    77  	if curve == nil {
    78  		return nil, errors.New("x509: unknown elliptic curve")
    79  	}
    80  	k := new(big.Int).SetBytes(privKey.PrivateKey)
    81  	curveOrder := curve.Params().N
    82  	if k.Cmp(curveOrder) >= 0 {
    83  		return nil, errors.New("x509: invalid elliptic curve private key value")
    84  	}
    85  	priv := new(ecdsa.PrivateKey)
    86  	priv.Curve = curve
    87  	priv.D = k
    88  	privateKey := make([]byte, (curveOrder.BitLen()+7)/8)
    89  	// Some private keys have leading zero padding. This is invalid
    90  	// according to [SEC1], but this code will ignore it.
    91  	for len(privKey.PrivateKey) > len(privateKey) {
    92  		if privKey.PrivateKey[0] != 0 {
    93  			return nil, errors.New("x509: invalid private key length")
    94  		}
    95  		privKey.PrivateKey = privKey.PrivateKey[1:]
    96  	}
    97  	// Some private keys remove all leading zeros, this is also invalid
    98  	// according to [SEC1] but since OpenSSL used to do this, we ignore
    99  	// this too.
   100  	copy(privateKey[len(privateKey)-len(privKey.PrivateKey):], privKey.PrivateKey)
   101  	priv.X, priv.Y = curve.ScalarBaseMult(privateKey)
   102  	return priv, nil
   103  }