-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathkeys.go
572 lines (488 loc) · 12.1 KB
/
keys.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
package crypto
import (
gocrypto "crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/sha256"
"crypto/sha512"
"crypto/subtle"
b64 "encoding/base64"
"encoding/json"
"fmt"
"io"
"strings"
scrypto "github.com/TBD54566975/ssi-sdk/crypto"
"github.com/TBD54566975/ssi-sdk/did/key"
cometcrypto "github.com/cometbft/cometbft/crypto"
"github.com/cometbft/cometbft/crypto/tmhash"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/lestrrat-go/jwx/v2/jwk"
ic "github.com/libp2p/go-libp2p/core/crypto"
icpb "github.com/libp2p/go-libp2p/core/crypto/pb"
"go.dedis.ch/kyber/v3"
"go.dedis.ch/kyber/v3/share"
"go.dedis.ch/kyber/v3/suites"
"golang.org/x/crypto/ripemd160"
)
type KeyType int32
func (kt KeyType) String() string {
if kt == 4 {
return "octet"
}
return icpb.KeyType(kt).String()
}
func KeyPairTypeFromString(keyType string) (KeyType, error) {
switch strings.ToLower(keyType) {
case "ed25519":
return Ed25519, nil
case "ecdsa":
return ECDSA, nil
case "secp256k1":
return Secp256k1, nil
default:
return 0, ErrBadKeyType
}
}
var (
Ed25519 = KeyType(icpb.KeyType_Ed25519)
ECDSA = KeyType(icpb.KeyType_ECDSA)
Secp256k1 = KeyType(icpb.KeyType_Secp256k1)
// Generic octet sequence ([]byte) for symetric keys, icpb.KeyType uses 0-3
Octet = KeyType(4)
)
type Key interface {
// Equals checks whether two keys are the same
Equals(Key) bool
// Raw returns the raw bytes of the key
Raw() ([]byte, error)
// Type returns the key type
Type() KeyType
}
func IsAsymmetric(key Key) bool {
switch key.(type) {
case PublicKey, PrivateKey:
return true
}
return false
}
func IsPublic(key Key) bool {
switch key.(type) {
case PublicKey:
return true
}
return false
}
func IsPrivate(key Key) bool {
switch key.(type) {
case PrivateKey:
return true
}
return false
}
func GetPublic(key Key) (PublicKey, error) {
if !IsAsymmetric(key) {
return nil, fmt.Errorf("key must be asymmetric")
}
switch kt := key.(type) {
case PublicKey:
return kt, nil
case PrivateKey:
return kt.GetPublic(), nil
}
return nil, fmt.Errorf("unknown key type")
}
func GetPrivate(key Key) (PrivateKey, error) {
if !IsAsymmetric(key) {
return nil, fmt.Errorf("key must by asymmetric")
}
priv, ok := key.(PrivateKey)
if !ok {
return nil, fmt.Errorf("key isn't private")
}
return priv, nil
}
// PublicKey
type PublicKey interface {
Key
Verify(data []byte, sig []byte) (bool, error)
Point() kyber.Point
Std() (gocrypto.PublicKey, error)
String() string
DID() (string, error)
}
var _ PublicKey = (*pubKeyLibP2P)(nil)
type pubKeyLibP2P struct {
ic.PubKey
suite suites.Suite
}
// PublicKeyFromLibP2P creates a PublicKey from a given
// LibP2P based PubKey
func PublicKeyFromLibP2P(pubkey ic.PubKey) (PublicKey, error) {
return publicKeyFromLibP2P(pubkey)
}
func PublicKeyFromProto(pk *icpb.PublicKey) (PublicKey, error) {
icpk, err := ic.PublicKeyFromProto(pk)
if err != nil {
return nil, err
}
return publicKeyFromLibP2P(icpk)
}
func PublicKeyFromStdPublicKey(pubkey gocrypto.PublicKey) (PublicKey, error) {
var icpk ic.PubKey
var err error
switch pkt := pubkey.(type) {
case ed25519.PublicKey:
icpk, err = ic.UnmarshalEd25519PublicKey(pkt)
case ecdsa.PublicKey:
icpk, err = ic.ECDSAPublicKeyFromPubKey(pkt)
case *ecdsa.PublicKey:
icpk, err = ic.ECDSAPublicKeyFromPubKey(*pkt)
case secp256k1.PublicKey:
sppk := ic.Secp256k1PublicKey(pkt)
icpk = &sppk
case *secp256k1.PublicKey:
icpk = (*ic.Secp256k1PublicKey)(pkt)
default:
return nil, fmt.Errorf("unknown key type")
}
if err != nil {
return nil, err
}
return publicKeyFromLibP2P(icpk)
}
func PublicKeyFromPoint(suite suites.Suite, point kyber.Point) (PublicKey, error) {
buf, err := point.MarshalBinary()
if err != nil {
return nil, fmt.Errorf("marshal point: %w", err)
}
var pk ic.PubKey
switch strings.ToLower(suite.String()) {
case "ed25519":
pk, err = ic.UnmarshalEd25519PublicKey(buf)
case "secp256k1":
pk, err = ic.UnmarshalSecp256k1PublicKey(buf)
case "ecdsa":
pk, err = ic.UnmarshalECDSAPublicKey(buf)
case "rsa":
pk, err = ic.UnmarshalRsaPublicKey(buf)
default:
return nil, ErrBadKeyType
}
if err != nil {
return nil, fmt.Errorf("unmarshal public key: %w", err)
}
return PublicKeyFromLibP2P(pk)
}
func PublicKeyFromBytes(keyType KeyType, buf []byte) (PublicKey, error) {
var pk ic.PubKey
var err error
switch keyType.String() {
case "ed25519":
pk, err = ic.UnmarshalEd25519PublicKey(buf)
case "secp256k1":
pk, err = ic.UnmarshalSecp256k1PublicKey(buf)
case "ecdsa":
pk, err = ic.UnmarshalECDSAPublicKey(buf)
case "rsa":
pk, err = ic.UnmarshalRsaPublicKey(buf)
default:
return nil, ErrBadKeyType
}
if err != nil {
return nil, fmt.Errorf("public key from bytes: %w", err)
}
return PublicKeyFromLibP2P(pk)
}
func publicKeyFromLibP2P(pubkey ic.PubKey) (*pubKeyLibP2P, error) {
suite, err := SuiteForType(KeyType(pubkey.Type()))
if err != nil {
return nil, err
}
return &pubKeyLibP2P{
PubKey: pubkey,
suite: suite,
}, nil
}
func ToLibP2PPublicKey(pk PublicKey) ic.PubKey {
return pk.(*pubKeyLibP2P).PubKey
}
func PublicKeyToProto(pk PublicKey) (*icpb.PublicKey, error) {
return ic.PublicKeyToProto(pk.(*pubKeyLibP2P).PubKey)
}
func (p *pubKeyLibP2P) Point() kyber.Point {
buf, _ := p.PubKey.Raw()
point := p.suite.Point()
point.UnmarshalBinary(buf)
return point
}
func (p *pubKeyLibP2P) Std() (gocrypto.PublicKey, error) {
// our version of "standard" secp256k1 keys uses the
// dcred type directly, as its more common among our
// dependencies (like go-jose)
switch pk := p.PubKey.(type) {
case *ic.Secp256k1PublicKey:
return (*secp256k1.PublicKey)(pk), nil
}
gokey, err := ic.PubKeyToStdKey(p.PubKey)
if err != nil {
return nil, err
}
// convert ed25519 keys to non pointers
switch kt := gokey.(type) {
case *ed25519.PublicKey:
return *kt, nil
}
return gokey, nil
}
func (p *pubKeyLibP2P) String() string {
buf, _ := p.Raw()
enc := b64.StdEncoding.EncodeToString(buf)
return enc
}
func (p *pubKeyLibP2P) DID() (string, error) {
didKeyType, err := cryptoKeyTypeToDID(p.Type())
if err != nil {
return "", err
}
keyBuf, err := p.Raw()
if err != nil {
return "", err
}
didKey, err := key.CreateDIDKey(didKeyType, keyBuf)
if err != nil {
return "", fmt.Errorf("creating did: %w", err)
}
return didKey.String(), nil
}
func (p *pubKeyLibP2P) MarshalJWK() ([]byte, error) {
goPubKey, err := ic.PubKeyToStdKey(p.PubKey)
if err != nil {
return nil, err
}
jPubKey, err := jwk.FromRaw(goPubKey)
if err != nil {
return nil, err
}
return json.Marshal(jPubKey)
}
func (p *pubKeyLibP2P) Type() KeyType {
// we can safely ignore this error
// since its already validated
return KeyType(p.PubKey.Type())
}
func (p *pubKeyLibP2P) Equals(k1 Key) bool {
if p == k1 {
return true
}
return basicEquals(p, k1)
}
func cryptoKeyTypeToDID(kt KeyType) (scrypto.KeyType, error) {
switch kt {
case Ed25519:
return scrypto.Ed25519, nil
case Secp256k1:
return scrypto.SECP256k1, nil
}
return "", fmt.Errorf("invalid key type")
}
func basicEquals(k1, k2 Key) bool {
if k1.Type() != k2.Type() {
return false
}
a, err := k1.Raw()
if err != nil {
return false
}
b, err := k2.Raw()
if err != nil {
return false
}
return subtle.ConstantTimeCompare(a, b) == 1
}
var _ PrivateKey = (*privKeyLibP2P)(nil)
type PrivateKey interface {
Key
Sign([]byte) ([]byte, error)
Scalar() kyber.Scalar
GetPublic() PublicKey
Std() (gocrypto.PrivateKey, error)
}
type privKeyLibP2P struct {
ic.PrivKey
suite suites.Suite
}
func GenerateKeyPair(keyType KeyType, src io.Reader) (PrivateKey, PublicKey, error) {
suite, err := SuiteForType(keyType)
if err != nil {
return nil, nil, err
}
sk, pk, err := ic.GenerateKeyPairWithReader(int(keyType), 0, src)
if err != nil {
return nil, nil, err
}
return &privKeyLibP2P{
PrivKey: sk,
suite: suite,
}, &pubKeyLibP2P{
PubKey: pk,
suite: suite,
}, nil
}
func PrivateKeyFromBytes(keyType KeyType, buf []byte) (PrivateKey, error) {
var pk ic.PrivKey
var err error
switch keyType {
case Ed25519:
pk, err = ic.UnmarshalEd25519PrivateKey(buf)
case Secp256k1:
pk, err = ic.UnmarshalSecp256k1PrivateKey(buf)
case ECDSA:
pk, err = ic.UnmarshalECDSAPrivateKey(buf)
// case "rsa":
// pk, err = ic.UnmarshalRsaPrivateKey(buf)
default:
return nil, ErrBadKeyType
}
if err != nil {
return nil, fmt.Errorf("public key from bytes: %w", err)
}
return PrivateKeyFromLibP2P(pk)
}
func PrivateKeyFromLibP2P(privkey ic.PrivKey) (PrivateKey, error) {
suite, err := SuiteForType(KeyType(privkey.Type()))
if err != nil {
return nil, err
}
return &privKeyLibP2P{
PrivKey: privkey,
suite: suite,
}, nil
}
func ToLibP2PPrivateKey(pk PrivateKey) ic.PrivKey {
return pk.(*privKeyLibP2P).PrivKey
}
func (p *privKeyLibP2P) Std() (gocrypto.PrivateKey, error) {
// our version of "standard" secp256k1 keys uses the
// dcred type directly, as its more common among our
// dependencies (like go-jose)
switch pk := p.PrivKey.(type) {
case *ic.Secp256k1PrivateKey:
return (*secp256k1.PrivateKey)(pk), nil
}
gokey, err := ic.PrivKeyToStdKey(p.PrivKey)
if err != nil {
return nil, err
}
// convert ed25519 keys to non pointers
switch kt := gokey.(type) {
case *ed25519.PrivateKey:
return *kt, nil
}
return gokey, nil
}
// Scalar returns a numeric elliptic curve scalar
// representation of the private key.
//
// WARNING: THIS ONLY WORKS WITH ED25519 & SECP256K1 CURVES RIGHT NOW.
func (p *privKeyLibP2P) Scalar() kyber.Scalar {
switch p.Type() {
case Ed25519:
return p.ed25519Scalar()
case Secp256k1:
return p.secp256k1Scalar()
default:
panic("only ed25519 and secp256k1 private key scalar conversion supported")
}
}
func (p *privKeyLibP2P) secp256k1Scalar() kyber.Scalar {
buf, err := p.Raw()
if err != nil {
panic(err) // todo
}
return p.suite.Scalar().SetBytes(buf)
}
func (p *privKeyLibP2P) ed25519Scalar() kyber.Scalar {
// There is a discrepency between LibP2P private keys
// and "raw" EC scalars. LibP2P private keys is an
// (x, y) pair, where x is the given "seed" and y is
// the cooresponding publickey. Where y is computed as
//
// h := sha512.Hash(x)
// s := scalar().SetWithClamp(h)
// y := point().ScalarBaseMul(x)
//
// So to make sure future conversions of this scalar
// to a public key, like in the DKG setup, we need to
// convert this key to a scalar using the Hash and Clamp
// method.
//
// To understand clamping, see here:
// https://neilmadden.blog/2020/05/28/whats-the-curve25519-clamping-all-about/
buf, err := p.PrivKey.Raw()
if err != nil {
panic(err)
}
// hash seed and clamp bytes
digest := sha512.Sum512(buf[:32])
digest[0] &= 0xf8
digest[31] &= 0x7f
digest[31] |= 0x40
return p.suite.Scalar().SetBytes(digest[:32])
}
func (p *privKeyLibP2P) GetPublic() PublicKey {
return &pubKeyLibP2P{
PubKey: p.PrivKey.GetPublic(),
suite: p.suite,
}
}
func (p *privKeyLibP2P) MarshalJWK() ([]byte, error) {
goPubKey, err := ic.PrivKeyToStdKey(p.PrivKey)
if err != nil {
return nil, err
}
jPubKey, err := jwk.FromRaw(goPubKey)
if err != nil {
return nil, err
}
return json.Marshal(jPubKey)
}
func (p *privKeyLibP2P) Type() KeyType {
return KeyType(p.PrivKey.Type())
}
func (p *privKeyLibP2P) Equals(k1 Key) bool {
if p == k1 {
return true
}
return basicEquals(p, k1)
}
// DistKeyShare
type DistKeyShare struct {
// Coefficients of the public polynomial holding the public key
Commits []kyber.Point
// PriShare of the distributed secret
PriShare *share.PriShare
}
// PubPoly
type PubPoly struct {
*share.PubPoly
}
func PublicKeyToBech32(pubkey PublicKey) (string, error) {
buf, err := pubkey.Raw()
if err != nil {
return "", fmt.Errorf("getting public key bytes: %w", err)
}
sum := tmhash.SumTruncated(buf)
return bech32.ConvertAndEncode("source", sum)
}
func PublicKeyBytesToBech32(pubkey []byte) (string, error) {
// convert to address
sha := sha256.Sum256(pubkey)
hasherRIPEMD160 := ripemd160.New()
hasherRIPEMD160.Write(sha[:]) // does not error
buf := cometcrypto.Address(hasherRIPEMD160.Sum(nil))
addr := sdk.AccAddress(buf)
// convert to bech32 (stringified address)
return addr.String(), nil
}