/
key.go
389 lines (354 loc) · 10.3 KB
/
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
* Copyright (C) 2019 The OnyxChain Authors
* This file is part of The OnyxChain library.
*
* The OnyxChain is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The OnyxChain is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The OnyxChain. If not, see <http://www.gnu.org/licenses/>.
*/
// Package keypair implements asymmetric key pair generation and some related
// functions.
//
// Multiple types of key pair supported:
// ECDSA
// SM2
// EdDSA
//
package keypair
import (
"bytes"
"crypto"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"math/big"
"reflect"
base58 "github.com/itchyny/base58-go"
"github.com/OnyxPay/OnyxChain-crypto/ec"
"golang.org/x/crypto/ed25519"
)
type PublicKey crypto.PublicKey
type PrivateKey interface {
crypto.PrivateKey
Public() crypto.PublicKey
}
type KeyType byte
// Supported key types
const (
PK_ECDSA KeyType = 0x12
PK_SM2 KeyType = 0x13
PK_EDDSA KeyType = 0x14
PK_P256_E KeyType = 0x02
PK_P256_O KeyType = 0x03
PK_P256_NC KeyType = 0x04
)
const err_generate = "key pair generation failed, "
// GenerateKeyPair generates a pair of private and public keys in type t.
// opts is the necessary parameter(s), which is defined by the key type:
// ECDSA: a byte specifies the elliptic curve, which defined in package ec
// SM2: same as ECDSA
// EdDSA: a byte specifies the curve, only ED25519 supported currently.
func GenerateKeyPair(t KeyType, opts interface{}) (PrivateKey, PublicKey, error) {
switch t {
case PK_ECDSA, PK_SM2:
param, ok := opts.(byte)
if !ok {
return nil, nil, errors.New(err_generate + "invalid EC options, 1 byte curve label excepted")
}
c, err := GetCurve(param)
if err != nil {
return nil, nil, errors.New(err_generate + err.Error())
}
if t == PK_ECDSA {
return ec.GenerateECKeyPair(c, rand.Reader, ec.ECDSA)
} else {
return ec.GenerateECKeyPair(c, rand.Reader, ec.SM2)
}
case PK_EDDSA:
param, ok := opts.(byte)
if !ok {
return nil, nil, errors.New(err_generate + "invalid EdDSA option")
}
if param == ED25519 {
pub, pri, err := ed25519.GenerateKey(rand.Reader)
return pri, pub, err
} else {
return nil, nil, errors.New(err_generate + "unsupported EdDSA scheme")
}
default:
return nil, nil, errors.New(err_generate + "unknown algorithm")
}
}
func GetKeyType(p PublicKey) KeyType {
switch t := p.(type) {
case *ec.PublicKey:
switch t.Algorithm {
case ec.ECDSA:
return PK_ECDSA
case ec.SM2:
return PK_SM2
default:
panic("unknown public key type")
}
case ed25519.PublicKey:
return PK_EDDSA
default:
panic("unknown public key type")
}
}
// SerializePublicKey serializes the public key to a byte sequence as the
// following format:
// |--------------------|-----------------|
// | algorithm (1 byte) | public_key_data |
// |--------------------|-----------------|
//
// public_key_data differs in the algorithm:
//
// - ECDSA & SM2
// |----------------|--------------------|
// | curve (1 byte) | encoded_public_key |
// |----------------|--------------------|
// encoded_public_key is the public key encoded in compression mode.
//
// - EdDSA
// Since only Ed25519 supported currently, it is just the 1 byte curve label
// followed by the byte sequence which could be handled as public key in
// package ed25519.
//
// ECDSA public key with NIST P-256 curve is treated as a special case, which
// just use the encoded data as the serialization and starts with 0x02 or 0x03,
// with no flags ahead.
//
// This function will panic if error occurs.
func SerializePublicKey(key PublicKey) []byte {
var buf bytes.Buffer
switch t := key.(type) {
case *ec.PublicKey:
switch t.Algorithm {
case ec.ECDSA:
// Take P-256 as a special case
if t.Params().Name == elliptic.P256().Params().Name {
return ec.EncodePublicKey(t.PublicKey, true)
}
buf.WriteByte(byte(PK_ECDSA))
case ec.SM2:
buf.WriteByte(byte(PK_SM2))
}
label, err := GetCurveLabel(t.Curve)
if err != nil {
panic(err)
}
buf.WriteByte(label)
buf.Write(ec.EncodePublicKey(t.PublicKey, true))
case ed25519.PublicKey:
buf.WriteByte(byte(PK_EDDSA))
buf.WriteByte(ED25519)
buf.Write([]byte(t))
default:
panic("unknown public key type")
}
return buf.Bytes()
}
// DeserializePublicKey parse the byte sequencce to a public key.
func DeserializePublicKey(data []byte) (PublicKey, error) {
if len(data) <= 3 {
return nil, errors.New("too short pubkey")
}
switch KeyType(data[0]) {
case PK_ECDSA, PK_SM2:
c, err := GetCurve(data[1])
if err != nil {
return nil, err
}
pub, err := ec.DecodePublicKey(data[2:], c)
if err != nil {
return nil, err
}
pk := &ec.PublicKey{PublicKey: pub}
switch KeyType(data[0]) {
case PK_ECDSA:
pk.Algorithm = ec.ECDSA
case PK_SM2:
pk.Algorithm = ec.SM2
default:
return nil, errors.New("deserializing public key failed: unknown EC algorithm")
}
return pk, nil
case PK_EDDSA:
if data[1] == ED25519 {
if len(data[2:]) != ed25519.PublicKeySize {
return nil, errors.New("deserializing public key failed: invalid length for Ed25519 public key")
}
pk := make([]byte, ed25519.PublicKeySize)
copy(pk, data[2:])
return ed25519.PublicKey(pk), nil
} else {
return nil, errors.New("deserializing public key failed: unsupported EdDSA scheme")
}
case PK_P256_E, PK_P256_O, PK_P256_NC:
pub, err := ec.DecodePublicKey(data, elliptic.P256())
if err != nil {
return nil, errors.New("deserializing public key failed: decode P-256 public key error")
}
pk := &ec.PublicKey{
Algorithm: ec.ECDSA,
PublicKey: pub,
}
return pk, nil
default:
return nil, errors.New("deserializing public key failed: unrecognized algorithm label")
}
}
// SerializePrivateKey serializes the input private key into byte array as the
// following format:
// |--------------------|------------------|
// | algorithm (1 byte) | private_key_data |
// |--------------------|------------------|
//
// The private_key_data differs in algorithm:
//
// - ECDSA & SM2
// |----------------|---------|--------------------|
// | curve (1 byte) | d_bytes | encoded_public_key |
// |----------------|---------|--------------------|
// d_bytes is the byte sequence converted from the integer d in little
// endian, with the byte length specified by the curve.
// encoded_public_key is the public key data encoded in comopression mode.
//
// - EdDSA
// Since only Ed25519 supported currently, it is just the 1 byte Ed25519
// curve label followed by the byte sequence which could be handled as
// private key in package ed25519.
//
// This function will panic if error occurs.
func SerializePrivateKey(pri PrivateKey) []byte {
var buf bytes.Buffer
switch t := pri.(type) {
case *ec.PrivateKey:
switch t.Algorithm {
case ec.ECDSA:
buf.WriteByte(byte(PK_ECDSA))
case ec.SM2:
buf.WriteByte(byte(PK_SM2))
}
label, err := GetCurveLabel(t.Curve)
if err != nil {
panic(err)
}
buf.WriteByte(label)
size := (t.Params().BitSize + 7) >> 3
dBytes := t.D.Bytes()
for i := len(dBytes); i < size; i++ {
buf.WriteByte(byte(0))
}
buf.Write(dBytes)
buf.Write(ec.EncodePublicKey(&t.PublicKey, true))
case ed25519.PrivateKey:
buf.WriteByte(byte(PK_EDDSA))
buf.WriteByte(byte(ED25519))
buf.Write(t)
default:
panic("unkown private key type")
}
return buf.Bytes()
}
// DeserializePrivateKey parses the input byte array into private key.
func DeserializePrivateKey(data []byte) (pri PrivateKey, err error) {
switch KeyType(data[0]) {
case PK_ECDSA, PK_SM2:
c, err1 := GetCurve(data[1])
if err1 != nil {
err = err1
return
}
size := (c.Params().BitSize + 7) >> 3
if len(data) < size*2+3 {
err = errors.New("deserializing private key failed: not enough length")
return
}
key := &ec.PrivateKey{
Algorithm: ec.ECDSA,
PrivateKey: ec.ConstructPrivateKey(data[2:2+size], c),
}
p, err1 := ec.DecodePublicKey(data[2+size:], c)
if err1 != nil {
err = fmt.Errorf("deserializing private key failed: %s", err1)
return
}
if key.X.Cmp(p.X) != 0 || key.Y.Cmp(p.Y) != 0 {
err = errors.New("deserializing private key failed: unmatched private and public key")
return
}
switch KeyType(data[0]) {
case PK_ECDSA:
key.Algorithm = ec.ECDSA
case PK_SM2:
key.Algorithm = ec.SM2
}
pri = key
case PK_EDDSA:
if data[1] == ED25519 {
if len(data) < 2+ed25519.PrivateKeySize {
err = errors.New("deserializing private key failed: not enough length for Ed25519 key")
return
}
pri = ed25519.PrivateKey(data[2:])
} else {
err = errors.New("deserializing private key failed: unknown EdDSA curve type")
return
}
}
return
}
// ComparePublicKey checks whether the two public key are the same.
func ComparePublicKey(k0, k1 PublicKey) bool {
if reflect.TypeOf(k0) != reflect.TypeOf(k1) {
return false
}
switch v0 := k0.(type) {
case *ec.PublicKey:
v1 := k1.(*ec.PublicKey)
if v0.Algorithm == v1.Algorithm && v0.Params().Name == v1.Params().Name && v0.X.Cmp(v1.X) == 0 {
return true
}
case ed25519.PublicKey:
v1 := k1.(ed25519.PublicKey)
if bytes.Compare(v0, v1) == 0 {
return true
}
}
return false
}
// Parse ECDSA P-256 private key in WIF
func GetP256KeyPairFromWIF(wif []byte) (PrivateKey, error) {
buf, err := base58.BitcoinEncoding.Decode(wif)
if err != nil {
return nil, err
}
bi, ok := new(big.Int).SetString(string(buf), 10)
clearBytes(buf)
if !ok || bi == nil {
return nil, errors.New("parse WIF error, invalid base58 data")
}
buf = bi.Bytes()
defer clearBytes(buf)
pos := len(buf) - 4
sum := sha256.Sum256(buf[:pos])
sum = sha256.Sum256(sum[:])
if !bytes.Equal(sum[:4], buf[pos:]) {
return nil, errors.New("invalid WIF data, checksum failed")
}
pri := ec.ConstructPrivateKey(buf[1:pos-1], elliptic.P256())
return &ec.PrivateKey{Algorithm: ec.ECDSA, PrivateKey: pri}, nil
}