Debian Codegraph @

keys/ecc/ecc.go

raw
1 //package ecc provides helpers for creating elliptic curve leys
2 package ecc
3
4 import (
5 "fmt"
6 "crypto/ecdsa"
7 "crypto/elliptic"
8 "crypto/x509"
9 "encoding/pem"
10 "errors"
11 "math/big"
12 )
13
14 // ReadPublic loads ecdsa.PublicKey from given PKCS1 X509 or PKIX blobs
15 func ReadPublic(raw []byte) (key *ecdsa.PublicKey, err error) {
16 var encoded *pem.Block
17
18 if encoded, _ = pem.Decode(raw); encoded == nil {
19 return nil, errors.New("Ecc.ReadPublic(): Key must be PEM encoded PKCS1 X509 certificate or PKIX EC public key")
20 }
21
22 var parsedKey interface{}
23 var cert *x509.Certificate
24
25 if parsedKey, err = x509.ParsePKIXPublicKey(encoded.Bytes); err != nil {
26 if cert, err = x509.ParseCertificate(encoded.Bytes); err != nil {
27 return nil, err
28 }
29
30 parsedKey = cert.PublicKey
31 }
32
33 var ok bool
34
35 if key, ok = parsedKey.(*ecdsa.PublicKey); !ok {
36 return nil, errors.New("Ecc.ReadPublic(): Key is not a valid *ecdsa.PublicKey")
37 }
38
39 return key, nil
40 }
41
42 // ReadPrivate loads ecdsa.PrivateKey from given PKCS1 or PKCS8 blobs
43 func ReadPrivate(raw []byte) (key *ecdsa.PrivateKey, err error) {
44 var encoded *pem.Block
45
46 if encoded, _ = pem.Decode(raw); encoded == nil {
47 return nil, errors.New("Ecc.ReadPrivate(): Key must be PEM encoded PKCS1 or PKCS8 EC private key")
48 }
49
50 var parsedKey interface{}
51
52 if parsedKey, err = x509.ParseECPrivateKey(encoded.Bytes); err != nil {
53 if parsedKey, err = x509.ParsePKCS8PrivateKey(encoded.Bytes); err != nil {
54 return nil, err
55 }
56 }
57
58 var ok bool
59
60 if key, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
61 return nil, errors.New("Ecc.ReadPrivate(): Key is not valid *ecdsa.PrivateKey")
62 }
63
64 return key, nil
65 }
66
67 // NewPublic constructs ecdsa.PublicKey from given (X,Y)
68 func NewPublic(x, y []byte) *ecdsa.PublicKey {
69 return &ecdsa.PublicKey{Curve: curve(len(x)),
70 X: new(big.Int).SetBytes(x),
71 Y: new(big.Int).SetBytes(y)}
72 }
73
74 // NewPrivate constructs ecdsa.PrivateKey from given (X,Y) and D
75 func NewPrivate(x, y, d []byte) *ecdsa.PrivateKey {
76 return &ecdsa.PrivateKey{D: new(big.Int).SetBytes(d),
77 PublicKey: ecdsa.PublicKey{Curve: curve(len(x)),
78 X: new(big.Int).SetBytes(x),
79 Y: new(big.Int).SetBytes(y)}}
80 }
81
82 func curve(size int) elliptic.Curve {
83 switch size {
84 case 31, 32:
85 return elliptic.P256()
86 case 48:
87 return elliptic.P384()
88 case 65, 66:
89 return elliptic.P521() //adjust for P-521 curve, which can be 65 or 66 bytes
90 default:
91 return nil //unsupported curve
92 }
93 }
94
95 func CurveByName(name string) (elliptic.Curve, error){
96 switch name {
97 case "P-256":
98 return elliptic.P256(), nil
99 case "P-384":
100 return elliptic.P384(), nil
101 case "P-521":
102 return elliptic.P521(), nil
103 default:
104 return nil, fmt.Errorf("Unsupported curve name: %s", name)
105 }
106 }
107