github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/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 // RFC5915 21 // SEC1 - http://www.secg.org/download/aid-780/sec1-v2.pdf 22 // Per RFC5915 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) (key *ecdsa.PrivateKey, err error) { 33 return parseECPrivateKey(nil, der) 34 } 35 36 // parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure. 37 // The OID for the named curve may be provided from another source (such as 38 // the PKCS8 container) - if it is provided then use this instead of the OID 39 // that may exist in the EC private key structure. 40 func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) { 41 var privKey ecPrivateKey 42 if _, err := asn1.Unmarshal(der, &privKey); err != nil { 43 return nil, errors.New("crypto/x509: failed to parse EC private key: " + err.Error()) 44 } 45 if privKey.Version != ecPrivKeyVersion { 46 return nil, fmt.Errorf("crypto/x509: unknown EC private key version %d", privKey.Version) 47 } 48 49 var curve elliptic.Curve 50 if namedCurveOID != nil { 51 curve = namedCurveFromOID(*namedCurveOID) 52 } else { 53 curve = namedCurveFromOID(privKey.NamedCurveOID) 54 } 55 if curve == nil { 56 return nil, errors.New("crypto/x509: unknown elliptic curve") 57 } 58 59 k := new(big.Int).SetBytes(privKey.PrivateKey) 60 if k.Cmp(curve.Params().N) >= 0 { 61 return nil, errors.New("crypto/x509: invalid elliptic curve private key value") 62 } 63 priv := new(ecdsa.PrivateKey) 64 priv.Curve = curve 65 priv.D = k 66 priv.X, priv.Y = curve.ScalarBaseMult(privKey.PrivateKey) 67 68 return priv, nil 69 }