/
ecc_key.go
331 lines (261 loc) · 7.43 KB
/
ecc_key.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package cmk
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/asn1"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"github.com/btcsuite/btcd/btcec/v2"
"math/big"
)
// We create our own type to manage JSON Marshaling
type EcdsaPrivateKey ecdsa.PrivateKey
type EccKey struct {
BaseKey
PrivateKey EcdsaPrivateKey
}
type ecdsaSignature struct {
R, S *big.Int
}
func NewEccKey(spec KeySpec, metadata KeyMetadata, policy string) (*EccKey, error) {
var curve elliptic.Curve
switch spec {
case SpecEccNistP256:
curve = elliptic.P256()
case SpecEccNistP384:
curve = elliptic.P384()
case SpecEccNistP521:
curve = elliptic.P521()
case SpecEccSecp256k1:
curve = btcec.S256()
default:
return nil, errors.New("key spec error")
}
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return nil, err
}
//---
k := &EccKey{
PrivateKey: EcdsaPrivateKey(*privateKey),
}
k.Type = TypeEcc
k.Metadata = metadata
k.Policy = policy
//---
k.Metadata.KeyUsage = UsageSignVerify
k.Metadata.KeySpec = spec
k.Metadata.CustomerMasterKeySpec = spec
switch spec {
case SpecEccNistP256:
k.Metadata.SigningAlgorithms = []SigningAlgorithm{SigningAlgorithmEcdsaSha256}
case SpecEccNistP384:
k.Metadata.SigningAlgorithms = []SigningAlgorithm{SigningAlgorithmEcdsaSha384}
case SpecEccNistP521:
k.Metadata.SigningAlgorithms = []SigningAlgorithm{SigningAlgorithmEcdsaSha512}
case SpecEccSecp256k1:
k.Metadata.SigningAlgorithms = []SigningAlgorithm{SigningAlgorithmEcdsaSha256}
default:
return nil, errors.New("unknown signing algorithm")
}
return k, nil
}
//----------------------------------------------------
func (k *EccKey) GetArn() string {
return k.GetMetadata().Arn
}
func (k *EccKey) GetPolicy() string {
return k.Policy
}
func (k *EccKey) GetKeyType() KeyType {
return k.Type
}
func (k *EccKey) GetMetadata() *KeyMetadata {
return &k.Metadata
}
//----------------------------------------------------
func (k *EccKey) Sign(digest []byte, algorithm SigningAlgorithm) ([]byte, error) {
//--------------------------
// Check the requested Signing Algorithm is supported by this key
validSigningAlgorithm := false
for _, a := range k.Metadata.SigningAlgorithms {
if a == algorithm {
validSigningAlgorithm = true
break
}
}
if !validSigningAlgorithm {
return []byte{}, &InvalidSigningAlgorithm{}
}
//--------------------------
// Check the digest is the correct length for the algorithm
switch algorithm {
case SigningAlgorithmEcdsaSha256:
if len(digest) != (256 / 8) {
return []byte{}, &InvalidDigestLength{}
}
case SigningAlgorithmEcdsaSha384:
if len(digest) != (384 / 8) {
return []byte{}, &InvalidDigestLength{}
}
case SigningAlgorithmEcdsaSha512:
if len(digest) != (512 / 8) {
return []byte{}, &InvalidDigestLength{}
}
default:
return []byte{}, errors.New("unknown signing algorithm")
}
//---
key := ecdsa.PrivateKey(k.PrivateKey)
r, s, err := ecdsa.Sign(rand.Reader, &key, digest)
if err != nil {
return []byte{}, err
}
return asn1.Marshal(ecdsaSignature{r, s})
}
func (k *EccKey) HashAndSign(message []byte, algorithm SigningAlgorithm) ([]byte, error) {
digest, err := hashMessage(message, algorithm)
if err != nil {
return []byte{}, err
}
return k.Sign(digest, algorithm)
}
//----------------------------------------------------
func (k *EccKey) Verify(signature []byte, digest []byte, algorithm SigningAlgorithm) (bool, error) {
ecdsaSignature := ecdsaSignature{}
_, err := asn1.Unmarshal(signature, &ecdsaSignature)
if err != nil {
return false, err
}
key := ecdsa.PrivateKey(k.PrivateKey)
valid := ecdsa.Verify(&key.PublicKey, digest, ecdsaSignature.R, ecdsaSignature.S)
return valid, nil
}
func (k *EccKey) HashAndVerify(signature []byte, message []byte, algorithm SigningAlgorithm) (bool, error) {
digest, err := hashMessage(message, algorithm)
if err != nil {
return false, err
}
return k.Verify(signature, digest, algorithm)
}
//----------------------------------------------------
type eccKeyMarshaledJSON struct {
D, X, Y *big.Int
CurveType string
}
func (k *EcdsaPrivateKey) MarshalJSON() ([]byte, error) {
return json.Marshal(&eccKeyMarshaledJSON{
D: k.D,
X: k.X,
Y: k.Y,
CurveType: k.Curve.Params().Name,
})
}
/*
ecdsa.PrivateKey.Curve is an interface type, so we need to
Unmarshal it ourselves to set the concrete type.
*/
func (k *EcdsaPrivateKey) UnmarshalJSON(data []byte) error {
var marshaledKey eccKeyMarshaledJSON
err := json.Unmarshal(data, &marshaledKey)
if err != nil {
return err
}
var pk ecdsa.PrivateKey
if marshaledKey.CurveType != "" {
// Keys generated with Go 1.20 and after
pk.D = marshaledKey.D
pk.X = marshaledKey.X
pk.Y = marshaledKey.Y
switch marshaledKey.CurveType {
case "P-256":
pk.Curve = elliptic.P256()
case "P-384":
pk.Curve = elliptic.P384()
case "P-521":
pk.Curve = elliptic.P521()
case "secp256k1":
pk.Curve = btcec.S256()
default:
return errors.New("trying to UnmarshalJSON unknown curve")
}
} else {
// Keys generated with Go 1.17 and before
pk.Curve = &elliptic.CurveParams{}
err = json.Unmarshal(data, &pk)
if err != nil {
return err
}
switch pk.Curve.Params().Name {
case "P-256":
pk.Curve = elliptic.P256()
case "P-384":
pk.Curve = elliptic.P384()
case "P-521":
pk.Curve = elliptic.P521()
case "secp256k1":
pk.Curve = btcec.S256()
default:
return errors.New("trying to UnmarshalJSON unknown curve")
}
}
*k = EcdsaPrivateKey(pk)
return nil
}
// ----------------------------------------------------
// Construct key from YAML (seeding)
// ---
func (k *EccKey) UnmarshalYAML(unmarshal func(interface{}) error) error {
// Cannot use embedded 'Key' struct
// https://github.com/go-yaml/yaml/issues/263
type YamlKey struct {
Metadata KeyMetadata `yaml:"Metadata"`
PrivateKeyPem string `yaml:"PrivateKeyPem"`
}
yk := YamlKey{}
if err := unmarshal(&yk); err != nil {
return &UnmarshalYAMLError{err.Error()}
}
k.Type = TypeEcc
k.Metadata = yk.Metadata
defaultSeededKeyMetadata(&k.Metadata)
pemDecoded, _ := pem.Decode([]byte(yk.PrivateKeyPem))
if pemDecoded == nil {
return &UnmarshalYAMLError{fmt.Sprintf("Unable to decode pem of key %s check the YAML.\n", k.Metadata.KeyId)}
}
parseResult, pkcsParseError := x509.ParseECPrivateKey(pemDecoded.Bytes)
if pkcsParseError != nil {
return &UnmarshalYAMLError{fmt.Sprintf("Unable to decode pem of key %s, Ensure it is in PKCS8 format with no password: %s.\n", k.Metadata.KeyId, pkcsParseError)}
}
k.PrivateKey = EcdsaPrivateKey(*parseResult)
var bitLen = parseResult.Curve.Params().BitSize
switch bitLen {
case 256:
k.Metadata.KeySpec = SpecEccNistP256
k.Metadata.SigningAlgorithms = []SigningAlgorithm{SigningAlgorithmEcdsaSha256}
case 384:
k.Metadata.KeySpec = SpecEccNistP384
k.Metadata.SigningAlgorithms = []SigningAlgorithm{SigningAlgorithmEcdsaSha384}
case 521:
k.Metadata.KeySpec = SpecEccNistP521
k.Metadata.SigningAlgorithms = []SigningAlgorithm{SigningAlgorithmEcdsaSha512}
default:
return &UnmarshalYAMLError{
fmt.Sprintf(
"EC Keysize must be one of (256,384,521) bits. %d bits found for key %s.\n",
bitLen, k.Metadata.KeyId),
}
}
k.Metadata.CustomerMasterKeySpec = k.Metadata.KeySpec
if k.Metadata.KeyUsage != UsageSignVerify {
return &UnmarshalYAMLError{
fmt.Sprintf(
"Only KeyUsage of (%s) supported for EC keys.\n", UsageSignVerify),
}
}
return nil
}