-
Notifications
You must be signed in to change notification settings - Fork 61
/
sm9_key.go
601 lines (536 loc) · 18.2 KB
/
sm9_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
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
package sm9
import (
"encoding/pem"
"errors"
"io"
"math/big"
"sync"
"github.com/emmansun/gmsm/internal/bigmod"
"github.com/emmansun/gmsm/sm9/bn256"
"golang.org/x/crypto/cryptobyte"
cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
)
// SignMasterPrivateKey master private key for sign, generated by KGC
type SignMasterPrivateKey struct {
SignMasterPublicKey // master public key
D *big.Int // master private key
}
// SignMasterPublicKey master public key for sign, generated by KGC
type SignMasterPublicKey struct {
MasterPublicKey *bn256.G2 // master public key
pairOnce sync.Once
basePoint *bn256.GT // the result of Pair(Gen1, pub.MasterPublicKey)
tableGenOnce sync.Once
table *[32 * 2]bn256.GTFieldTable // precomputed basePoint^n
}
// SignPrivateKey user private key for sign, generated by KGC
type SignPrivateKey struct {
PrivateKey *bn256.G1 // user private key
SignMasterPublicKey // master public key
}
// EncryptMasterPrivateKey master private key for encryption, generated by KGC
type EncryptMasterPrivateKey struct {
EncryptMasterPublicKey // master public key
D *big.Int // master private key
}
// EncryptMasterPublicKey master private key for encryption, generated by KGC
type EncryptMasterPublicKey struct {
MasterPublicKey *bn256.G1 // public key
pairOnce sync.Once
basePoint *bn256.GT // the result of Pair(pub.MasterPublicKey, Gen2)
tableGenOnce sync.Once
table *[32 * 2]bn256.GTFieldTable // precomputed basePoint^n
}
// EncryptPrivateKey user private key for encryption, generated by KGC
type EncryptPrivateKey struct {
PrivateKey *bn256.G2 // user private key
EncryptMasterPublicKey // master public key
}
// GenerateSignMasterKey generates a master public and private key pair for DSA usage.
func GenerateSignMasterKey(rand io.Reader) (*SignMasterPrivateKey, error) {
k, err := randomScalar(rand)
if err != nil {
return nil, err
}
kBytes := k.Bytes(orderNat)
p, err := new(bn256.G2).ScalarBaseMult(kBytes)
if err != nil {
return nil, err
}
priv := new(SignMasterPrivateKey)
priv.D = new(big.Int).SetBytes(kBytes)
priv.MasterPublicKey = p
return priv, nil
}
// MarshalASN1 marshal sign master private key to asn.1 format data according
// SM9 cryptographic algorithm application specification
func (master *SignMasterPrivateKey) MarshalASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BigInt(master.D)
return b.Bytes()
}
// UnmarshalASN1 unmarsal der data to sign master private key
func (master *SignMasterPrivateKey) UnmarshalASN1(der []byte) error {
input := cryptobyte.String(der)
d := &big.Int{}
var inner cryptobyte.String
var pubBytes []byte
if der[0] == 0x30 {
if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) ||
!input.Empty() ||
!inner.ReadASN1Integer(d) {
return errors.New("sm9: invalid sign master private key asn1 data")
}
// Just parse it, did't validate it
if !inner.Empty() && (!inner.ReadASN1BitStringAsBytes(&pubBytes) || !inner.Empty()) {
return errors.New("sm9: invalid sign master public key asn1 data")
}
} else if !input.ReadASN1Integer(d) || !input.Empty() {
return errors.New("sm9: invalid sign master private key asn1 data")
}
master.D = d
p, err := new(bn256.G2).ScalarBaseMult(bn256.NormalizeScalar(d.Bytes()))
if err != nil {
return err
}
master.MasterPublicKey = p
return nil
}
// GenerateUserKey generate an user dsa key.
func (master *SignMasterPrivateKey) GenerateUserKey(uid []byte, hid byte) (*SignPrivateKey, error) {
var id []byte
id = append(id, uid...)
id = append(id, hid)
t1Nat := hashH1(id)
d, err := bigmod.NewNat().SetBytes(master.D.Bytes(), orderNat)
if err != nil {
return nil, err
}
t1Nat.Add(d, orderNat)
if t1Nat.IsZero() == 1 {
return nil, errors.New("sm9: need to re-generate sign master private key")
}
t1Nat = bigmod.NewNat().Exp(t1Nat, orderMinus2, orderNat)
t1Nat.Mul(d, orderNat)
priv := new(SignPrivateKey)
priv.SignMasterPublicKey = master.SignMasterPublicKey
g1, err := new(bn256.G1).ScalarBaseMult(t1Nat.Bytes(orderNat))
if err != nil {
return nil, err
}
priv.PrivateKey = g1
return priv, nil
}
// Public returns the public key corresponding to priv.
func (master *SignMasterPrivateKey) Public() *SignMasterPublicKey {
return &master.SignMasterPublicKey
}
// pair generate the basepoint once
func (pub *SignMasterPublicKey) pair() *bn256.GT {
pub.pairOnce.Do(func() {
pub.basePoint = bn256.Pair(bn256.Gen1, pub.MasterPublicKey)
})
return pub.basePoint
}
func (pub *SignMasterPublicKey) generatorTable() *[32 * 2]bn256.GTFieldTable {
pub.tableGenOnce.Do(func() {
pub.table = bn256.GenerateGTFieldTable(pub.pair())
})
return pub.table
}
// ScalarBaseMult compute basepoint^r with precomputed table
// The base point = pair(Gen1, <master public key>)
func (pub *SignMasterPublicKey) ScalarBaseMult(scalar []byte) (*bn256.GT, error) {
tables := pub.generatorTable()
return bn256.ScalarBaseMultGT(tables, scalar)
}
// GenerateUserPublicKey generate user sign public key
func (pub *SignMasterPublicKey) GenerateUserPublicKey(uid []byte, hid byte) *bn256.G2 {
var buffer []byte
buffer = append(buffer, uid...)
buffer = append(buffer, hid)
h1 := hashH1(buffer)
p, err := new(bn256.G2).ScalarBaseMult(h1.Bytes(orderNat))
if err != nil {
panic(err)
}
p.Add(p, pub.MasterPublicKey)
return p
}
// MarshalASN1 marshal sign master public key to asn.1 format data according
// SM9 cryptographic algorithm application specification
func (pub *SignMasterPublicKey) MarshalASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BitString(pub.MasterPublicKey.MarshalUncompressed())
return b.Bytes()
}
// MarshalCompressedASN1 marshal sign master public key to asn.1 format data according
// SM9 cryptographic algorithm application specification, the curve point is in compressed form.
func (pub *SignMasterPublicKey) MarshalCompressedASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BitString(pub.MasterPublicKey.MarshalCompressed())
return b.Bytes()
}
func unmarshalG2(bytes []byte) (*bn256.G2, error) {
g2 := new(bn256.G2)
switch bytes[0] {
case 4:
_, err := g2.Unmarshal(bytes[1:])
if err != nil {
return nil, err
}
case 2, 3:
_, err := g2.UnmarshalCompressed(bytes)
if err != nil {
return nil, err
}
default:
return nil, errors.New("sm9: invalid point identity byte")
}
return g2, nil
}
// UnmarshalRaw unmarsal raw bytes data to sign master public key
func (pub *SignMasterPublicKey) UnmarshalRaw(bytes []byte) error {
g2, err := unmarshalG2(bytes)
if err != nil {
return err
}
pub.MasterPublicKey = g2
return nil
}
// UnmarshalASN1 unmarsal der data to sign master public key
func (pub *SignMasterPublicKey) UnmarshalASN1(der []byte) error {
var bytes []byte
var inner cryptobyte.String
input := cryptobyte.String(der)
if der[0] == 0x30 {
if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) ||
!input.Empty() ||
!inner.ReadASN1BitStringAsBytes(&bytes) ||
!inner.Empty() {
return errors.New("sm9: invalid sign master public key asn1 data")
}
} else if !input.ReadASN1BitStringAsBytes(&bytes) || !input.Empty() {
return errors.New("sm9: invalid sign master public key asn1 data")
}
return pub.UnmarshalRaw(bytes)
}
// ParseFromPEM just for GMSSL, there are no Algorithm pkix.AlgorithmIdentifier
func (pub *SignMasterPublicKey) ParseFromPEM(data []byte) error {
block, _ := pem.Decode([]byte(data))
if block == nil {
return errors.New("sm9: failed to parse PEM block")
}
return pub.UnmarshalASN1(block.Bytes)
}
// MasterPublic returns the master public key corresponding to priv.
func (priv *SignPrivateKey) MasterPublic() *SignMasterPublicKey {
return &priv.SignMasterPublicKey
}
// SetMasterPublicKey bind the sign master public key to it.
func (priv *SignPrivateKey) SetMasterPublicKey(pub *SignMasterPublicKey) {
if priv.SignMasterPublicKey.MasterPublicKey == nil {
priv.SignMasterPublicKey = *pub
}
}
// MarshalASN1 marshal sign user private key to asn.1 format data according
// SM9 cryptographic algorithm application specification
func (priv *SignPrivateKey) MarshalASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BitString(priv.PrivateKey.MarshalUncompressed())
return b.Bytes()
}
// MarshalCompressedASN1 marshal sign user private key to asn.1 format data according
// SM9 cryptographic algorithm application specification, the curve point is in compressed form.
func (priv *SignPrivateKey) MarshalCompressedASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BitString(priv.PrivateKey.MarshalCompressed())
return b.Bytes()
}
func unmarshalG1(bytes []byte) (*bn256.G1, error) {
g := new(bn256.G1)
switch bytes[0] {
case 4:
_, err := g.Unmarshal(bytes[1:])
if err != nil {
return nil, err
}
case 2, 3:
_, err := g.UnmarshalCompressed(bytes)
if err != nil {
return nil, err
}
default:
return nil, errors.New("sm9: invalid point identity byte")
}
return g, nil
}
// UnmarshalRaw unmarsal raw bytes data to sign user private key
// Note, priv's SignMasterPublicKey should be handled separately.
func (priv *SignPrivateKey) UnmarshalRaw(bytes []byte) error {
g, err := unmarshalG1(bytes)
if err != nil {
return err
}
priv.PrivateKey = g
return nil
}
// UnmarshalASN1 unmarsal der data to sign user private key
// Note, priv's SignMasterPublicKey should be handled separately.
func (priv *SignPrivateKey) UnmarshalASN1(der []byte) error {
var bytes []byte
var pubBytes []byte
var inner cryptobyte.String
input := cryptobyte.String(der)
if der[0] == 0x30 {
if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) ||
!input.Empty() ||
!inner.ReadASN1BitStringAsBytes(&bytes) {
return errors.New("sm9: invalid sign user private key asn1 data")
}
if !inner.Empty() && (!inner.ReadASN1BitStringAsBytes(&pubBytes) || !inner.Empty()) {
return errors.New("sm9: invalid sign master public key asn1 data")
}
} else if !input.ReadASN1BitStringAsBytes(&bytes) || !input.Empty() {
return errors.New("sm9: invalid sign user private key asn1 data")
}
err := priv.UnmarshalRaw(bytes)
if err != nil {
return err
}
if len(pubBytes) > 0 {
masterPK := new(SignMasterPublicKey)
err = masterPK.UnmarshalRaw(pubBytes)
if err != nil {
return err
}
priv.SetMasterPublicKey(masterPK)
}
return nil
}
// GenerateEncryptMasterKey generates a master public and private key pair for encryption usage.
func GenerateEncryptMasterKey(rand io.Reader) (*EncryptMasterPrivateKey, error) {
k, err := randomScalar(rand)
if err != nil {
return nil, err
}
kBytes := k.Bytes(orderNat)
priv := new(EncryptMasterPrivateKey)
priv.D = new(big.Int).SetBytes(kBytes)
p, err := new(bn256.G1).ScalarBaseMult(kBytes)
if err != nil {
panic(err)
}
priv.MasterPublicKey = p
return priv, nil
}
// GenerateUserKey generate an user key for encryption.
func (master *EncryptMasterPrivateKey) GenerateUserKey(uid []byte, hid byte) (*EncryptPrivateKey, error) {
var id []byte
id = append(id, uid...)
id = append(id, hid)
t1Nat := hashH1(id)
d, err := bigmod.NewNat().SetBytes(master.D.Bytes(), orderNat)
if err != nil {
return nil, err
}
t1Nat.Add(d, orderNat)
if t1Nat.IsZero() == 1 {
return nil, errors.New("sm9: need to re-generate encrypt master private key")
}
t1Nat = bigmod.NewNat().Exp(t1Nat, orderMinus2, orderNat)
t1Nat.Mul(d, orderNat)
priv := new(EncryptPrivateKey)
priv.EncryptMasterPublicKey = master.EncryptMasterPublicKey
p, err := new(bn256.G2).ScalarBaseMult(t1Nat.Bytes(orderNat))
if err != nil {
panic(err)
}
priv.PrivateKey = p
return priv, nil
}
// Public returns the public key corresponding to priv.
func (master *EncryptMasterPrivateKey) Public() *EncryptMasterPublicKey {
return &master.EncryptMasterPublicKey
}
// MarshalASN1 marshal encrypt master private key to asn.1 format data according
// SM9 cryptographic algorithm application specification
func (master *EncryptMasterPrivateKey) MarshalASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BigInt(master.D)
return b.Bytes()
}
// UnmarshalASN1 unmarsal der data to encrypt master private key
func (master *EncryptMasterPrivateKey) UnmarshalASN1(der []byte) error {
input := cryptobyte.String(der)
d := &big.Int{}
var inner cryptobyte.String
var pubBytes []byte
if der[0] == 0x30 {
if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) ||
!input.Empty() ||
!inner.ReadASN1Integer(d) {
return errors.New("sm9: invalid encrypt master private key asn1 data")
}
// Just parse it, did't validate it
if !inner.Empty() && (!inner.ReadASN1BitStringAsBytes(&pubBytes) || !inner.Empty()) {
return errors.New("sm9: invalid encrypt master public key asn1 data")
}
} else if !input.ReadASN1Integer(d) || !input.Empty() {
return errors.New("sm9: invalid encrypt master private key asn1 data")
}
master.D = d
p, err := new(bn256.G1).ScalarBaseMult(bn256.NormalizeScalar(d.Bytes()))
if err != nil {
return err
}
master.MasterPublicKey = p
return nil
}
// pair generate the basepoint once
func (pub *EncryptMasterPublicKey) pair() *bn256.GT {
pub.pairOnce.Do(func() {
pub.basePoint = bn256.Pair(pub.MasterPublicKey, bn256.Gen2)
})
return pub.basePoint
}
func (pub *EncryptMasterPublicKey) generatorTable() *[32 * 2]bn256.GTFieldTable {
pub.tableGenOnce.Do(func() {
pub.table = bn256.GenerateGTFieldTable(pub.pair())
})
return pub.table
}
// ScalarBaseMult compute basepoint^r with precomputed table.
// The base point = pair(<master public key>, Gen2)
func (pub *EncryptMasterPublicKey) ScalarBaseMult(scalar []byte) (*bn256.GT, error) {
tables := pub.generatorTable()
return bn256.ScalarBaseMultGT(tables, scalar)
}
// GenerateUserPublicKey generate user encrypt public key
func (pub *EncryptMasterPublicKey) GenerateUserPublicKey(uid []byte, hid byte) *bn256.G1 {
var buffer []byte
buffer = append(buffer, uid...)
buffer = append(buffer, hid)
h1 := hashH1(buffer)
p, err := new(bn256.G1).ScalarBaseMult(h1.Bytes(orderNat))
if err != nil {
panic(err)
}
p.Add(p, pub.MasterPublicKey)
return p
}
// MarshalASN1 marshal encrypt master public key to asn.1 format data according
// SM9 cryptographic algorithm application specification
func (pub *EncryptMasterPublicKey) MarshalASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BitString(pub.MasterPublicKey.MarshalUncompressed())
return b.Bytes()
}
// MarshalCompressedASN1 marshal encrypt master public key to asn.1 format data according
// SM9 cryptographic algorithm application specification, the curve point is in compressed form.
func (pub *EncryptMasterPublicKey) MarshalCompressedASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BitString(pub.MasterPublicKey.MarshalCompressed())
return b.Bytes()
}
// UnmarshalRaw unmarsal raw bytes data to encrypt master public key
func (pub *EncryptMasterPublicKey) UnmarshalRaw(bytes []byte) error {
g, err := unmarshalG1(bytes)
if err != nil {
return err
}
pub.MasterPublicKey = g
return nil
}
// ParseFromPEM just for GMSSL, there are no Algorithm pkix.AlgorithmIdentifier
func (pub *EncryptMasterPublicKey) ParseFromPEM(data []byte) error {
block, _ := pem.Decode([]byte(data))
if block == nil {
return errors.New("sm9: failed to parse PEM block")
}
return pub.UnmarshalASN1(block.Bytes)
}
// UnmarshalASN1 unmarsal der data to encrypt master public key
func (pub *EncryptMasterPublicKey) UnmarshalASN1(der []byte) error {
var bytes []byte
var inner cryptobyte.String
input := cryptobyte.String(der)
if der[0] == 0x30 {
if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) ||
!input.Empty() ||
!inner.ReadASN1BitStringAsBytes(&bytes) ||
!inner.Empty() {
return errors.New("sm9: invalid encrypt master public key asn1 data")
}
} else if !input.ReadASN1BitStringAsBytes(&bytes) || !input.Empty() {
return errors.New("sm9: invalid encrypt master public key asn1 data")
}
return pub.UnmarshalRaw(bytes)
}
// MasterPublic returns the master public key corresponding to priv.
func (priv *EncryptPrivateKey) MasterPublic() *EncryptMasterPublicKey {
return &priv.EncryptMasterPublicKey
}
// SetMasterPublicKey bind the encrypt master public key to it.
func (priv *EncryptPrivateKey) SetMasterPublicKey(pub *EncryptMasterPublicKey) {
if priv.EncryptMasterPublicKey.MasterPublicKey == nil {
priv.EncryptMasterPublicKey = *pub
}
}
// MarshalASN1 marshal encrypt user private key to asn.1 format data according
// SM9 cryptographic algorithm application specification
func (priv *EncryptPrivateKey) MarshalASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BitString(priv.PrivateKey.MarshalUncompressed())
return b.Bytes()
}
// MarshalCompressedASN1 marshal encrypt user private key to asn.1 format data according
// SM9 cryptographic algorithm application specification, the curve point is in compressed form.
func (priv *EncryptPrivateKey) MarshalCompressedASN1() ([]byte, error) {
var b cryptobyte.Builder
b.AddASN1BitString(priv.PrivateKey.MarshalCompressed())
return b.Bytes()
}
// UnmarshalRaw unmarsal raw bytes data to encrypt user private key
// Note, priv's EncryptMasterPublicKey should be handled separately.
func (priv *EncryptPrivateKey) UnmarshalRaw(bytes []byte) error {
g, err := unmarshalG2(bytes)
if err != nil {
return err
}
priv.PrivateKey = g
return nil
}
// UnmarshalASN1 unmarsal der data to encrypt user private key
// Note, priv's EncryptMasterPublicKey should be handled separately.
func (priv *EncryptPrivateKey) UnmarshalASN1(der []byte) error {
var bytes []byte
var pubBytes []byte
var inner cryptobyte.String
input := cryptobyte.String(der)
if der[0] == 0x30 {
if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) ||
!input.Empty() ||
!inner.ReadASN1BitStringAsBytes(&bytes) {
return errors.New("sm9: invalid encrypt user private key asn1 data")
}
if !inner.Empty() && (!inner.ReadASN1BitStringAsBytes(&pubBytes) || !inner.Empty()) {
return errors.New("sm9: invalid encrypt master public key asn1 data")
}
} else if !input.ReadASN1BitStringAsBytes(&bytes) || !input.Empty() {
return errors.New("sm9: invalid encrypt user private key asn1 data")
}
err := priv.UnmarshalRaw(bytes)
if err != nil {
return err
}
if len(pubBytes) > 0 {
masterPK := new(EncryptMasterPublicKey)
err = masterPK.UnmarshalRaw(pubBytes)
if err != nil {
return err
}
priv.SetMasterPublicKey(masterPK)
}
return nil
}