...
1
2
3
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
19
20
21
22
23
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
32
33
34 func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error) {
35 return parseECPrivateKey(nil, der)
36 }
37
38
39
40
41
42
43 func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error) {
44 oid, ok := oidFromNamedCurve(key.Curve)
45 if !ok {
46 return nil, errors.New("x509: unknown elliptic curve")
47 }
48
49 return marshalECPrivateKeyWithOID(key, oid)
50 }
51
52
53
54 func marshalECPrivateKeyWithOID(key *ecdsa.PrivateKey, oid asn1.ObjectIdentifier) ([]byte, error) {
55 privateKey := make([]byte, (key.Curve.Params().N.BitLen()+7)/8)
56 return asn1.Marshal(ecPrivateKey{
57 Version: 1,
58 PrivateKey: key.D.FillBytes(privateKey),
59 NamedCurveOID: oid,
60 PublicKey: asn1.BitString{Bytes: elliptic.Marshal(key.Curve, key.X, key.Y)},
61 })
62 }
63
64
65
66
67
68 func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {
69 var privKey ecPrivateKey
70 if _, err := asn1.Unmarshal(der, &privKey); err != nil {
71 if _, err := asn1.Unmarshal(der, &pkcs8{}); err == nil {
72 return nil, errors.New("x509: failed to parse private key (use ParsePKCS8PrivateKey instead for this key format)")
73 }
74 if _, err := asn1.Unmarshal(der, &pkcs1PrivateKey{}); err == nil {
75 return nil, errors.New("x509: failed to parse private key (use ParsePKCS1PrivateKey instead for this key format)")
76 }
77 return nil, errors.New("x509: failed to parse EC private key: " + err.Error())
78 }
79 if privKey.Version != ecPrivKeyVersion {
80 return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version)
81 }
82
83 var curve elliptic.Curve
84 if namedCurveOID != nil {
85 curve = namedCurveFromOID(*namedCurveOID)
86 } else {
87 curve = namedCurveFromOID(privKey.NamedCurveOID)
88 }
89 if curve == nil {
90 return nil, errors.New("x509: unknown elliptic curve")
91 }
92
93 k := new(big.Int).SetBytes(privKey.PrivateKey)
94 curveOrder := curve.Params().N
95 if k.Cmp(curveOrder) >= 0 {
96 return nil, errors.New("x509: invalid elliptic curve private key value")
97 }
98 priv := new(ecdsa.PrivateKey)
99 priv.Curve = curve
100 priv.D = k
101
102 privateKey := make([]byte, (curveOrder.BitLen()+7)/8)
103
104
105
106 for len(privKey.PrivateKey) > len(privateKey) {
107 if privKey.PrivateKey[0] != 0 {
108 return nil, errors.New("x509: invalid private key length")
109 }
110 privKey.PrivateKey = privKey.PrivateKey[1:]
111 }
112
113
114
115
116 copy(privateKey[len(privateKey)-len(privKey.PrivateKey):], privKey.PrivateKey)
117 priv.X, priv.Y = curve.ScalarBaseMult(privateKey)
118
119 return priv, nil
120 }
121
View as plain text