forked from flyinox/fabric-sm-patch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfabric-sm-patch
19718 lines (19692 loc) · 782 KB
/
fabric-sm-patch
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
From 841de2aca9cd65f02543a0861f180d9ba8d53355 Mon Sep 17 00:00:00 2001
From: Dijun Liu <[email protected]>
Date: Wed, 7 Nov 2018 11:48:02 +0800
Subject: [PATCH] China crypto standards support
---
bccsp/factory/gmfactory.go | 42 +
bccsp/factory/nopkcs11.go | 4 +-
bccsp/factory/pkcs11.go | 4 +-
bccsp/gm/fileks.go | 407 ++
bccsp/gm/impl.go | 379 ++
bccsp/gm/keys.go | 415 ++
bccsp/gm/sm2.go | 78 +
bccsp/gm/sm2key.go | 119 +
bccsp/sm2opts.go | 119 +
bccsp/utils/keys.go | 3 +-
common/tools/cryptogen/ca/generator.go | 2 +
common/tools/cryptogen/ca/generatorsm.go | 241 +
common/tools/cryptogen/csp/csp.go | 2 +
common/tools/cryptogen/csp/cspsm.go | 164 +
common/tools/cryptogen/main.go | 2 +
common/tools/cryptogen/mainsm.go | 719 +++
common/tools/cryptogen/msp/generator.go | 2 +
common/tools/cryptogen/msp/generatorsm.go | 284 +
docker-env.mk | 2 +-
examples/plugins/smPlugin/fileks.go | 407 ++
examples/plugins/smPlugin/impl.go | 372 ++
examples/plugins/smPlugin/keys.go | 415 ++
examples/plugins/smPlugin/sm2.go | 78 +
examples/plugins/smPlugin/sm2key.go | 119 +
msp/cert.go | 3 +-
msp/identities.go | 30 +-
msp/mspimpl.go | 3 +-
msp/mspimplsetup.go | 3 +-
msp/mspimplvalidate.go | 3 +-
.../flyinox/crypto/sm/sm2/p256sm2.go | 51 +
.../github.com/flyinox/crypto/sm/sm2/sm2.go | 166 +
.../flyinox/crypto/sm/sm2/sm2_test.go | 114 +
.../github.com/flyinox/crypto/sm/sm3/sm3.go | 146 +
.../flyinox/crypto/sm/sm3/sm3_test.go | 83 +
.../flyinox/crypto/sm/sm3/sm3hash.go | 172 +
.../github.com/flyinox/crypto/sm/sm4/sm4.go | 190 +
.../flyinox/crypto/sm/sm4/sm4_test.go | 50 +
.../flyinox/crypto/x509/cert_pool.go | 170 +
.../flyinox/crypto/x509/example_test.go | 134 +
.../flyinox/crypto/x509/pem_decrypt.go | 240 +
.../flyinox/crypto/x509/pem_decrypt_test.go | 247 +
.../github.com/flyinox/crypto/x509/pkcs1.go | 121 +
.../github.com/flyinox/crypto/x509/pkcs8.go | 55 +
.../flyinox/crypto/x509/pkcs8_test.go | 28 +
vendor/github.com/flyinox/crypto/x509/root.go | 22 +
.../flyinox/crypto/x509/root_bsd.go | 15 +
.../flyinox/crypto/x509/root_cgo_darwin.go | 236 +
.../flyinox/crypto/x509/root_darwin.go | 264 +
.../crypto/x509/root_darwin_arm_gen.go | 192 +
.../flyinox/crypto/x509/root_darwin_armx.go | 4908 +++++++++++++++++
.../flyinox/crypto/x509/root_darwin_test.go | 80 +
.../flyinox/crypto/x509/root_linux.go | 14 +
.../flyinox/crypto/x509/root_nacl.go | 8 +
.../flyinox/crypto/x509/root_nocgo_darwin.go | 11 +
.../flyinox/crypto/x509/root_plan9.go | 37 +
.../flyinox/crypto/x509/root_solaris.go | 12 +
.../flyinox/crypto/x509/root_unix.go | 88 +
.../flyinox/crypto/x509/root_unix_test.go | 127 +
.../flyinox/crypto/x509/root_windows.go | 266 +
vendor/github.com/flyinox/crypto/x509/sec1.go | 162 +
.../flyinox/crypto/x509/sec1_test.go | 44 +
.../flyinox/crypto/x509/sha2_windows_test.go | 19 +
.../flyinox/crypto/x509/test-file.crt | 32 +
.../github.com/flyinox/crypto/x509/verify.go | 565 ++
.../flyinox/crypto/x509/verify_test.go | 1694 ++++++
vendor/github.com/flyinox/crypto/x509/x509.go | 2395 ++++++++
.../flyinox/crypto/x509/x509_test.go | 1425 +++++
.../flyinox/crypto/x509/x509_test_import.go | 53 +
68 files changed, 19044 insertions(+), 13 deletions(-)
create mode 100644 bccsp/factory/gmfactory.go
create mode 100644 bccsp/gm/fileks.go
create mode 100644 bccsp/gm/impl.go
create mode 100644 bccsp/gm/keys.go
create mode 100644 bccsp/gm/sm2.go
create mode 100644 bccsp/gm/sm2key.go
create mode 100644 bccsp/sm2opts.go
create mode 100644 common/tools/cryptogen/ca/generatorsm.go
create mode 100644 common/tools/cryptogen/csp/cspsm.go
create mode 100644 common/tools/cryptogen/mainsm.go
create mode 100644 common/tools/cryptogen/msp/generatorsm.go
create mode 100644 examples/plugins/smPlugin/fileks.go
create mode 100644 examples/plugins/smPlugin/impl.go
create mode 100644 examples/plugins/smPlugin/keys.go
create mode 100644 examples/plugins/smPlugin/sm2.go
create mode 100644 examples/plugins/smPlugin/sm2key.go
create mode 100644 vendor/github.com/flyinox/crypto/sm/sm2/p256sm2.go
create mode 100644 vendor/github.com/flyinox/crypto/sm/sm2/sm2.go
create mode 100644 vendor/github.com/flyinox/crypto/sm/sm2/sm2_test.go
create mode 100644 vendor/github.com/flyinox/crypto/sm/sm3/sm3.go
create mode 100644 vendor/github.com/flyinox/crypto/sm/sm3/sm3_test.go
create mode 100644 vendor/github.com/flyinox/crypto/sm/sm3/sm3hash.go
create mode 100644 vendor/github.com/flyinox/crypto/sm/sm4/sm4.go
create mode 100644 vendor/github.com/flyinox/crypto/sm/sm4/sm4_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/cert_pool.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/example_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/pem_decrypt.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/pem_decrypt_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/pkcs1.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/pkcs8.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/pkcs8_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_bsd.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_cgo_darwin.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_darwin.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_darwin_arm_gen.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_darwin_armx.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_darwin_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_linux.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_nacl.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_nocgo_darwin.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_plan9.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_solaris.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_unix.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_unix_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/root_windows.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/sec1.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/sec1_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/sha2_windows_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/test-file.crt
create mode 100644 vendor/github.com/flyinox/crypto/x509/verify.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/verify_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/x509.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/x509_test.go
create mode 100644 vendor/github.com/flyinox/crypto/x509/x509_test_import.go
diff --git a/bccsp/factory/gmfactory.go b/bccsp/factory/gmfactory.go
new file mode 100644
index 000000000..71b44b2db
--- /dev/null
+++ b/bccsp/factory/gmfactory.go
@@ -0,0 +1,42 @@
+/*
+Copyright IBM Corp. All Rights Reserved.
+
+SPDX-License-Identifier: Apache-2.0
+*/
+package factory
+
+import (
+ "errors"
+ "github.com/hyperledger/fabric/bccsp"
+ "github.com/hyperledger/fabric/bccsp/gm"
+)
+
+const (
+ // PluginFactoryName is the factory name for BCCSP plugins
+ GMFactoryName = "SW"
+)
+
+// PluginFactory is the factory for BCCSP plugins
+type GMFactory struct{}
+
+// Name returns the name of this factory
+func (f *GMFactory) Name() string {
+ return GMFactoryName
+}
+
+// Get returns an instance of BCCSP using Opts.
+func (f *GMFactory) Get(config *FactoryOpts) (bccsp.BCCSP, error) {
+ // Validate arguments
+ if config == nil || config.SwOpts == nil {
+ return nil, errors.New("Invalid config. It must not be nil.")
+ }
+
+ swOpts := config.SwOpts
+
+ var keystore string
+ if swOpts.FileKeystore != nil && swOpts.Ephemeral != true {
+ keystore = swOpts.FileKeystore.KeyStorePath
+ }
+
+ return gm.New(keystore)
+}
diff --git a/bccsp/factory/nopkcs11.go b/bccsp/factory/nopkcs11.go
index a83695fa6..77125fecf 100644
--- a/bccsp/factory/nopkcs11.go
+++ b/bccsp/factory/nopkcs11.go
@@ -53,7 +53,7 @@ func InitFactories(config *FactoryOpts) error {
// Software-Based BCCSP
if config.SwOpts != nil {
- f := &SWFactory{}
+ f := &GMFactory{}
err := initBCCSP(f, config)
if err != nil {
factoriesInitError = errors.Wrapf(err, "Failed initializing BCCSP.")
@@ -84,7 +84,7 @@ func GetBCCSPFromOpts(config *FactoryOpts) (bccsp.BCCSP, error) {
var f BCCSPFactory
switch config.ProviderName {
case "SW":
- f = &SWFactory{}
+ f = &GMFactory{}
case "PLUGIN":
f = &PluginFactory{}
default:
diff --git a/bccsp/factory/pkcs11.go b/bccsp/factory/pkcs11.go
index 4456d70eb..cd8eba27c 100644
--- a/bccsp/factory/pkcs11.go
+++ b/bccsp/factory/pkcs11.go
@@ -62,7 +62,7 @@ func setFactories(config *FactoryOpts) error {
// Software-Based BCCSP
if config.SwOpts != nil {
- f := &SWFactory{}
+ f := &GMFactory{}
err := initBCCSP(f, config)
if err != nil {
factoriesInitError = errors.Wrap(err, "Failed initializing SW.BCCSP")
@@ -101,7 +101,7 @@ func GetBCCSPFromOpts(config *FactoryOpts) (bccsp.BCCSP, error) {
var f BCCSPFactory
switch config.ProviderName {
case "SW":
- f = &SWFactory{}
+ f = &GMFactory{}
case "PKCS11":
f = &PKCS11Factory{}
case "PLUGIN":
diff --git a/bccsp/gm/fileks.go b/bccsp/gm/fileks.go
new file mode 100644
index 000000000..af93dd917
--- /dev/null
+++ b/bccsp/gm/fileks.go
@@ -0,0 +1,407 @@
+/*
+Copyright IBM Corp. 2016 All Rights Reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+package gm
+
+import (
+ "bytes"
+ "io/ioutil"
+ "os"
+ "sync"
+
+ "errors"
+ "strings"
+
+ "encoding/hex"
+ "fmt"
+ "path/filepath"
+
+ "github.com/flyinox/crypto/sm/sm2"
+ "github.com/hyperledger/fabric/bccsp"
+ "github.com/hyperledger/fabric/bccsp/sw"
+ "github.com/hyperledger/fabric/bccsp/utils"
+)
+
+// NewFileBasedKeyStore instantiated a file-based key store at a given position.
+// The key store can be encrypted if a non-empty password is specifiec.
+// It can be also be set as read only. In this case, any store operation
+// will be forbidden
+func NewFileBasedKeyStore(pwd []byte, path string, readOnly bool) (bccsp.KeyStore, error) {
+ o, err := sw.NewFileBasedKeyStore(pwd, path, readOnly)
+ if err != nil {
+ return nil, err
+ }
+ ks := &fileBasedKeyStore{k: o}
+ return ks, ks.Init(pwd, path, readOnly)
+}
+
+// fileBasedKeyStore is a folder-based KeyStore.
+// Each key is stored in a separated file whose name contains the key's SKI
+// and flags to identity the key's type. All the keys are stored in
+// a folder whose path is provided at initialization time.
+// The KeyStore can be initialized with a password, this password
+// is used to encrypt and decrypt the files storing the keys.
+// A KeyStore can be read only to avoid the overwriting of keys.
+type fileBasedKeyStore struct {
+ path string
+
+ readOnly bool
+ isOpen bool
+
+ pwd []byte
+
+ // Sync
+ m sync.Mutex
+
+ k bccsp.KeyStore
+}
+
+// Init initializes this KeyStore with a password, a path to a folder
+// where the keys are stored and a read only flag.
+// Each key is stored in a separated file whose name contains the key's SKI
+// and flags to identity the key's type.
+// If the KeyStore is initialized with a password, this password
+// is used to encrypt and decrypt the files storing the keys.
+// The pwd can be nil for non-encrypted KeyStores. If an encrypted
+// key-store is initialized without a password, then retrieving keys from the
+// KeyStore will fail.
+// A KeyStore can be read only to avoid the overwriting of keys.
+func (ks *fileBasedKeyStore) Init(pwd []byte, path string, readOnly bool) error {
+ // Validate inputs
+ // pwd can be nil
+
+ if len(path) == 0 {
+ return errors.New("An invalid KeyStore path provided. Path cannot be an empty string.")
+ }
+
+ ks.m.Lock()
+ defer ks.m.Unlock()
+
+ if ks.isOpen {
+ return errors.New("KeyStore already initilized.")
+ }
+
+ ks.path = path
+ ks.pwd = utils.Clone(pwd)
+
+ err := ks.createKeyStoreIfNotExists()
+ if err != nil {
+ return err
+ }
+
+ err = ks.openKeyStore()
+ if err != nil {
+ return err
+ }
+
+ ks.readOnly = readOnly
+
+ return nil
+}
+
+// ReadOnly returns true if this KeyStore is read only, false otherwise.
+// If ReadOnly is true then StoreKey will fail.
+func (ks *fileBasedKeyStore) ReadOnly() bool {
+ return ks.readOnly
+}
+
+// GetKey returns a key object whose SKI is the one passed.
+func (ks *fileBasedKeyStore) GetKey(ski []byte) (k bccsp.Key, err error) {
+ // Validate arguments
+ if len(ski) == 0 {
+ return nil, errors.New("Invalid SKI. Cannot be of zero length.")
+ }
+
+ suffix := ks.getSuffix(hex.EncodeToString(ski))
+
+ switch suffix {
+ case "sk":
+ // Load the private key
+ key, err := ks.loadPrivateKey(hex.EncodeToString(ski))
+ if err != nil {
+ return nil, fmt.Errorf("Failed loading secret key [%x] [%s]", ski, err)
+ }
+
+ switch key.(type) {
+ case *sm2.PrivateKey:
+ return &sm2PrivateKey{key.(*sm2.PrivateKey)}, nil
+ default:
+ return ks.k.GetKey(ski)
+ }
+ case "pk":
+ // Load the public key
+ key, err := ks.loadPublicKey(hex.EncodeToString(ski))
+ if err != nil {
+ return nil, fmt.Errorf("Failed loading public key [%x] [%s]", ski, err)
+ }
+
+ switch key.(type) {
+ case *sm2.PublicKey:
+ return &sm2PublicKey{key.(*sm2.PublicKey)}, nil
+ default:
+ return ks.k.GetKey(ski)
+ }
+ default:
+ key, err := ks.searchKeystoreForSKI(ski)
+ if err != nil {
+ return ks.k.GetKey(ski)
+ }
+ return key, nil
+ }
+}
+
+// StoreKey stores the key k in this KeyStore.
+// If this KeyStore is read only then the method will fail.
+func (ks *fileBasedKeyStore) StoreKey(k bccsp.Key) (err error) {
+ if ks.readOnly {
+ return errors.New("Read only KeyStore.")
+ }
+
+ if k == nil {
+ return errors.New("Invalid key. It must be different from nil.")
+ }
+ switch k.(type) {
+ case *sm2PrivateKey:
+ kk := k.(*sm2PrivateKey)
+
+ err = ks.storePrivateKey(hex.EncodeToString(k.SKI()), kk.privKey)
+ if err != nil {
+ return fmt.Errorf("Failed storing sm2 private key [%s]", err)
+ }
+ case *sm2PublicKey:
+ kk := k.(*sm2PublicKey)
+
+ err = ks.storePublicKey(hex.EncodeToString(k.SKI()), kk.pubKey)
+ if err != nil {
+ return fmt.Errorf("Failed storing sm2 public key [%s]", err)
+ }
+
+ default:
+ return ks.k.StoreKey(k)
+ }
+
+ return
+}
+
+func (ks *fileBasedKeyStore) searchKeystoreForSKI(ski []byte) (k bccsp.Key, err error) {
+
+ files, _ := ioutil.ReadDir(ks.path)
+ for _, f := range files {
+ if f.IsDir() {
+ continue
+ }
+
+ if f.Size() > (1 << 16) { //64k, somewhat arbitrary limit, considering even large RSA keys
+ continue
+ }
+
+ raw, err := ioutil.ReadFile(filepath.Join(ks.path, f.Name()))
+ if err != nil {
+ continue
+ }
+
+ key, err := PEMtoPrivateKey(raw, ks.pwd)
+ if err != nil {
+ continue
+ }
+
+ switch key.(type) {
+ case *sm2.PrivateKey:
+ k = &sm2PrivateKey{key.(*sm2.PrivateKey)}
+ default:
+ continue
+ }
+
+ if !bytes.Equal(k.SKI(), ski) {
+ continue
+ }
+
+ return k, nil
+ }
+ return nil, fmt.Errorf("Key with SKI %s not found in %s", hex.EncodeToString(ski), ks.path)
+}
+
+func (ks *fileBasedKeyStore) getSuffix(alias string) string {
+ files, _ := ioutil.ReadDir(ks.path)
+ for _, f := range files {
+ if strings.HasPrefix(f.Name(), alias) {
+ if strings.HasSuffix(f.Name(), "sk") {
+ return "sk"
+ }
+ if strings.HasSuffix(f.Name(), "pk") {
+ return "pk"
+ }
+ if strings.HasSuffix(f.Name(), "key") {
+ return "key"
+ }
+ break
+ }
+ }
+ return ""
+}
+
+func (ks *fileBasedKeyStore) storePrivateKey(alias string, privateKey interface{}) error {
+ rawKey, err := PrivateKeyToPEM(privateKey, ks.pwd)
+ if err != nil {
+ logger.Errorf("Failed converting private key to PEM [%s]: [%s]", alias, err)
+ return err
+ }
+
+ err = ioutil.WriteFile(ks.getPathForAlias(alias, "sk"), rawKey, 0700)
+ if err != nil {
+ logger.Errorf("Failed storing private key [%s]: [%s]", alias, err)
+ return err
+ }
+
+ return nil
+}
+
+func (ks *fileBasedKeyStore) storePublicKey(alias string, publicKey interface{}) error {
+ rawKey, err := PublicKeyToPEM(publicKey, ks.pwd)
+ if err != nil {
+ logger.Errorf("Failed converting public key to PEM [%s]: [%s]", alias, err)
+ return err
+ }
+
+ err = ioutil.WriteFile(ks.getPathForAlias(alias, "pk"), rawKey, 0700)
+ if err != nil {
+ logger.Errorf("Failed storing private key [%s]: [%s]", alias, err)
+ return err
+ }
+
+ return nil
+}
+
+func (ks *fileBasedKeyStore) storeKey(alias string, key []byte) error {
+ pem, err := utils.AEStoEncryptedPEM(key, ks.pwd)
+ if err != nil {
+ logger.Errorf("Failed converting key to PEM [%s]: [%s]", alias, err)
+ return err
+ }
+
+ err = ioutil.WriteFile(ks.getPathForAlias(alias, "key"), pem, 0700)
+ if err != nil {
+ logger.Errorf("Failed storing key [%s]: [%s]", alias, err)
+ return err
+ }
+
+ return nil
+}
+
+func (ks *fileBasedKeyStore) loadPrivateKey(alias string) (interface{}, error) {
+ path := ks.getPathForAlias(alias, "sk")
+ logger.Debugf("Loading private key [%s] at [%s]...", alias, path)
+
+ raw, err := ioutil.ReadFile(path)
+ if err != nil {
+ logger.Errorf("Failed loading private key [%s]: [%s].", alias, err.Error())
+
+ return nil, err
+ }
+
+ privateKey, err := PEMtoPrivateKey(raw, ks.pwd)
+ if err != nil {
+ logger.Errorf("Failed parsing private key [%s]: [%s].", alias, err.Error())
+
+ return nil, err
+ }
+
+ return privateKey, nil
+}
+
+func (ks *fileBasedKeyStore) loadPublicKey(alias string) (interface{}, error) {
+ path := ks.getPathForAlias(alias, "pk")
+ logger.Debugf("Loading public key [%s] at [%s]...", alias, path)
+
+ raw, err := ioutil.ReadFile(path)
+ if err != nil {
+ logger.Errorf("Failed loading public key [%s]: [%s].", alias, err.Error())
+
+ return nil, err
+ }
+
+ privateKey, err := PEMtoPublicKey(raw, ks.pwd)
+ if err != nil {
+ logger.Errorf("Failed parsing private key [%s]: [%s].", alias, err.Error())
+
+ return nil, err
+ }
+
+ return privateKey, nil
+}
+
+func (ks *fileBasedKeyStore) loadKey(alias string) ([]byte, error) {
+ path := ks.getPathForAlias(alias, "key")
+ logger.Debugf("Loading key [%s] at [%s]...", alias, path)
+
+ pem, err := ioutil.ReadFile(path)
+ if err != nil {
+ logger.Errorf("Failed loading key [%s]: [%s].", alias, err.Error())
+
+ return nil, err
+ }
+
+ key, err := PEMtoAES(pem, ks.pwd)
+ if err != nil {
+ logger.Errorf("Failed parsing key [%s]: [%s]", alias, err)
+
+ return nil, err
+ }
+
+ return key, nil
+}
+
+func (ks *fileBasedKeyStore) createKeyStoreIfNotExists() error {
+ // Check keystore directory
+ ksPath := ks.path
+ missing, err := utils.DirMissingOrEmpty(ksPath)
+
+ if missing {
+ logger.Debugf("KeyStore path [%s] missing [%t]: [%s]", ksPath, missing, utils.ErrToString(err))
+
+ err := ks.createKeyStore()
+ if err != nil {
+ logger.Errorf("Failed creating KeyStore At [%s]: [%s]", ksPath, err.Error())
+ return nil
+ }
+ }
+
+ return nil
+}
+
+func (ks *fileBasedKeyStore) createKeyStore() error {
+ // Create keystore directory root if it doesn't exist yet
+ ksPath := ks.path
+ logger.Debugf("Creating KeyStore at [%s]...", ksPath)
+
+ os.MkdirAll(ksPath, 0755)
+
+ logger.Debugf("KeyStore created at [%s].", ksPath)
+ return nil
+}
+
+func (ks *fileBasedKeyStore) openKeyStore() error {
+ if ks.isOpen {
+ return nil
+ }
+
+ logger.Debugf("KeyStore opened at [%s]...done", ks.path)
+
+ return nil
+}
+
+func (ks *fileBasedKeyStore) getPathForAlias(alias, suffix string) string {
+ return filepath.Join(ks.path, alias+"_"+suffix)
+}
diff --git a/bccsp/gm/impl.go b/bccsp/gm/impl.go
new file mode 100644
index 000000000..3dded0389
--- /dev/null
+++ b/bccsp/gm/impl.go
@@ -0,0 +1,379 @@
+/*
+Copyright IBM Corp. All Rights Reserved.
+
+SPDX-License-Identifier: Apache-2.0
+*/
+package gm
+
+import (
+ "hash"
+
+ "crypto/rand"
+ "fmt"
+ "math/big"
+
+ "github.com/flyinox/crypto/sm/sm2"
+ "github.com/flyinox/crypto/sm/sm3"
+ "github.com/flyinox/crypto/x509"
+
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/hyperledger/fabric/bccsp"
+ "github.com/hyperledger/fabric/bccsp/sw"
+ "github.com/hyperledger/fabric/common/flogging"
+ coreconfig "github.com/hyperledger/fabric/core/config"
+ "github.com/pkg/errors"
+ "github.com/spf13/viper"
+)
+
+var (
+ logger = flogging.MustGetLogger("plugin_sm")
+)
+
+type impl struct {
+ sw bccsp.BCCSP
+ ks bccsp.KeyStore
+}
+
+func getKeyStoreDir(keystore string) (string, error) {
+ viperconfig := viper.New()
+ viperconfig.AutomaticEnv()
+ replacer := strings.NewReplacer(".", "_")
+ viperconfig.SetEnvKeyReplacer(replacer)
+
+ if keystore == "" {
+ switch strings.Split(filepath.Base(os.Args[0]), "_")[0] {
+ case "peer":
+ viperconfig.SetEnvPrefix("CORE")
+ coreconfig.InitViper(viperconfig, "core")
+ if err := viperconfig.ReadInConfig(); err != nil {
+ return "", fmt.Errorf("Error reading configuration: %s", err)
+ }
+ return filepath.Join(viper.GetString("peer.mspConfigPath"), "keystore"), nil
+ case "orderer":
+ viperconfig.SetEnvPrefix("ORDERER")
+ coreconfig.InitViper(viperconfig, "orderer")
+ if err := viperconfig.ReadInConfig(); err != nil {
+ return "", fmt.Errorf("Error reading configuration: %s", err)
+ }
+ return filepath.Join(viperconfig.GetString("General.LocalMSPDir"), "keystore"), nil
+ default:
+ return "", nil
+ }
+ }
+
+ return keystore, nil
+}
+
+// New returns a new instance of the BCCSP implementation
+func New(keystore string) (bccsp.BCCSP, error) {
+
+ var (
+ swCsp bccsp.BCCSP
+ ks bccsp.KeyStore
+ err error
+ )
+
+ keyStorePath, err := getKeyStoreDir(keystore)
+ if err != nil {
+ return nil, err
+ }
+
+ if keyStorePath == ""{
+ ks = sw.NewDummyKeyStore()
+ swCsp,err = sw.NewDefaultSecurityLevelWithKeystore(ks)
+ if err != nil {
+ return nil, err
+ }
+ return &impl{sw: swCsp, ks: ks}, nil
+ }
+
+ swCsp, err = sw.NewDefaultSecurityLevel(keyStorePath)
+ if err != nil {
+ return nil, err
+ }
+
+ ks, err = NewFileBasedKeyStore(nil, keyStorePath, false)
+ if err != nil {
+ return nil, err
+ }
+
+ return &impl{sw: swCsp, ks: ks}, nil
+}
+
+// KeyGen generates a key using opts.
+func (csp *impl) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) {
+ switch opts.(type) {
+ case *bccsp.SM2KeyGenOpts:
+ privKey, err := sm2.GenerateKey(rand.Reader)
+ if err != nil {
+ return nil, fmt.Errorf("Failed generating SM2 key for : [%s]", err)
+ }
+
+ k = &sm2PrivateKey{privKey}
+
+ if !opts.Ephemeral() {
+ // Store the key
+ err = csp.ks.StoreKey(k)
+ if err != nil {
+ return nil, errors.Wrapf(err, "Failed storing imported key with opts [%v]", opts)
+ }
+ }
+
+ return k, nil
+ default:
+ return csp.sw.KeyGen(opts)
+ }
+
+}
+
+// KeyDeriv derives a key from k using opts.
+// The opts argument should be appropriate for the primitive used.
+func (csp *impl) KeyDeriv(k bccsp.Key, opts bccsp.KeyDerivOpts) (dk bccsp.Key, err error) {
+ switch k := k.(type) {
+ case *sm2PrivateKey:
+ // Validate opts
+ if opts == nil {
+ return nil, errors.New("Invalid opts parameter. It must not be nil.")
+ }
+
+ sm2K := k
+
+ switch opts.(type) {
+ // Re-randomized an ECDSA private key
+ case *bccsp.SM2ReRandKeyOpts:
+ reRandOpts := opts.(*bccsp.SM2ReRandKeyOpts)
+ tempSK := &sm2.PrivateKey{
+ PublicKey: sm2.PublicKey{
+ Curve: sm2K.privKey.Curve,
+ X: new(big.Int),
+ Y: new(big.Int),
+ },
+ D: new(big.Int),
+ }
+
+ var k = new(big.Int).SetBytes(reRandOpts.ExpansionValue())
+ var one = new(big.Int).SetInt64(1)
+ n := new(big.Int).Sub(sm2K.privKey.Params().N, one)
+ k.Mod(k, n)
+ k.Add(k, one)
+
+ tempSK.D.Add(sm2K.privKey.D, k)
+ tempSK.D.Mod(tempSK.D, sm2K.privKey.PublicKey.Params().N)
+
+ // Compute temporary public key
+ tempX, tempY := sm2K.privKey.PublicKey.ScalarBaseMult(k.Bytes())
+ tempSK.PublicKey.X, tempSK.PublicKey.Y =
+ tempSK.PublicKey.Add(
+ sm2K.privKey.PublicKey.X, sm2K.privKey.PublicKey.Y,
+ tempX, tempY,
+ )
+
+ // Verify temporary public key is a valid point on the reference curve
+ isOn := tempSK.Curve.IsOnCurve(tempSK.PublicKey.X, tempSK.PublicKey.Y)
+ if !isOn {
+ return nil, errors.New("Failed temporary public key IsOnCurve check.")
+ }
+
+ return &sm2PrivateKey{tempSK}, nil
+ default:
+ return nil, fmt.Errorf("Unsupported 'KeyDerivOpts' provided [%v]", opts)
+ }
+ case *sm2PublicKey:
+ // Validate opts
+ if opts == nil {
+ return nil, errors.New("Invalid opts parameter. It must not be nil.")
+ }
+
+ sm2K := k
+
+ switch opts.(type) {
+ // Re-randomized an ECDSA private key
+ case *bccsp.SM2ReRandKeyOpts:
+ reRandOpts := opts.(*bccsp.SM2ReRandKeyOpts)
+ tempSK := &sm2.PublicKey{
+ Curve: sm2K.pubKey.Curve,
+ X: new(big.Int),
+ Y: new(big.Int),
+ }
+
+ var k = new(big.Int).SetBytes(reRandOpts.ExpansionValue())
+ var one = new(big.Int).SetInt64(1)
+ n := new(big.Int).Sub(sm2K.pubKey.Params().N, one)
+ k.Mod(k, n)
+ k.Add(k, one)
+
+ // Compute temporary public key
+ tempX, tempY := sm2K.pubKey.ScalarBaseMult(k.Bytes())
+ tempSK.X, tempSK.Y = tempSK.Add(
+ sm2K.pubKey.X, sm2K.pubKey.Y,
+ tempX, tempY,
+ )
+
+ // Verify temporary public key is a valid point on the reference curve
+ isOn := tempSK.Curve.IsOnCurve(tempSK.X, tempSK.Y)
+ if !isOn {
+ return nil, errors.New("Failed temporary public key IsOnCurve check.")
+ }
+
+ return &sm2PublicKey{tempSK}, nil
+ default:
+ return nil, fmt.Errorf("Unsupported 'KeyDerivOpts' provided [%v]", opts)
+ }
+ default:
+ return csp.sw.KeyDeriv(k, opts)
+ }
+}
+
+// KeyImport imports a key from its raw representation using opts.
+// The opts argument should be appropriate for the primitive used.
+func (csp *impl) KeyImport(raw interface{}, opts bccsp.KeyImportOpts) (k bccsp.Key, err error) {
+ switch opts.(type) {
+ case *bccsp.SM2PKIXPublicKeyImportOpts:
+ der, ok := raw.([]byte)
+ if !ok {
+ return nil, errors.New("Invalid raw material. Expected byte array.")
+ }
+
+ if len(der) == 0 {
+ return nil, errors.New("Invalid raw. It must not be nil.")
+ }
+
+ lowLevelKey, err := DERToPublicKey(der)
+ if err != nil {
+ return nil, fmt.Errorf("Failed converting PKIX to ECDSA public key [%s]", err)
+ }
+
+ sm2PK, ok := lowLevelKey.(*sm2.PublicKey)
+ if !ok {
+ return nil, errors.New("Failed casting to ECDSA public key. Invalid raw material.")
+ }
+
+ return &sm2PublicKey{sm2PK}, nil
+ case *bccsp.SM2PrivateKeyImportOpts:
+ der, ok := raw.([]byte)
+ if !ok {
+ return nil, errors.New("[SM2PrivateKeyImportOpts] Invalid raw material. Expected byte array.")
+ }
+
+ if len(der) == 0 {
+ return nil, errors.New("[SM2PrivateKeyImportOpts] Invalid raw. It must not be nil.")
+ }
+
+ lowLevelKey, err := DERToPrivateKey(der)
+ if err != nil {
+ return nil, fmt.Errorf("Failed converting PKIX to SM2 private key [%s]", err)
+ }
+
+ sm2SK, ok := lowLevelKey.(*sm2.PrivateKey)
+ if !ok {
+ return nil, errors.New("Failed casting to SM2 private key. Invalid raw material.")
+ }
+
+ return &sm2PrivateKey{sm2SK}, nil
+ case *bccsp.SM2GoPublicKeyImportOpts:
+ lowLevelKey, ok := raw.(*sm2.PublicKey)
+ if !ok {
+ return nil, errors.New("Invalid raw material. Expected *sm2.PublicKey.")
+ }
+
+ return &sm2PublicKey{lowLevelKey}, nil
+ case *bccsp.X509PublicKeyImportOpts:
+ x509Cert, ok := raw.(*x509.Certificate)
+ if !ok {
+ return nil, errors.New("Invalid raw material. Expected *x509.Certificate.")
+ }
+
+ //if pk, ok := x509Cert.PublicKey.(*sm2.PublicKey); ok {
+ // return &sm2PublicKey{pk}, nil
+ //} else {
+ // return csp.sw.KeyImport(raw, opts)
+ //}
+ pk := x509Cert.PublicKey
+
+ switch pk.(type) {
+ case *sm2.PublicKey:
+ return &sm2PublicKey{pk.(*sm2.PublicKey)}, nil
+ default:
+ return csp.sw.KeyImport(raw, opts)
+ }
+ default:
+ return csp.sw.KeyImport(raw, opts)
+ }
+}
+
+// GetKey returns the key this CSP associates to
+// the Subject Key Identifier ski.
+func (csp *impl) GetKey(ski []byte) (k bccsp.Key, err error) {
+ if k, err := csp.ks.GetKey(ski); err == nil {
+ return k, err
+ } else {
+ return csp.sw.GetKey(ski)
+ }
+}
+
+// Hash hashes messages msg using options opts.
+// If opts is nil, the default hash function will be used.
+func (csp *impl) Hash(msg []byte, opts bccsp.HashOpts) (hash []byte, err error) {
+ switch opts.(type) {
+ case *bccsp.SM3Opts:
+ h := sm3.New()
+ h.Write(msg)
+ return h.Sum(nil), nil
+ default:
+ return csp.sw.Hash(msg, opts)
+ }
+}
+
+// GetHash returns and instance of hash.Hash using options opts.
+// If opts is nil, the default hash function will be returned.
+func (csp *impl) GetHash(opts bccsp.HashOpts) (h hash.Hash, err error) {
+ switch opts.(type) {
+ case *bccsp.SM3Opts:
+ return sm3.New(), nil
+ default:
+ return csp.sw.GetHash(opts)
+ }
+}
+
+// Sign signs digest using key k.
+// The opts argument should be appropriate for the algorithm used.
+//
+// Note that when a signature of a hash of a larger message is needed,
+// the caller is responsible for hashing the larger message and passing
+// the hash (as digest).
+func (csp *impl) Sign(k bccsp.Key, digest []byte, opts bccsp.SignerOpts) (signature []byte, err error) {
+ switch k := k.(type) {
+ case *sm2PrivateKey:
+ return signSM2(k.privKey, digest, opts)
+ default:
+ return csp.sw.Sign(k, digest, opts)
+ }
+}
+
+// Verify verifies signature against key k and digest
+// The opts argument should be appropriate for the algorithm used.
+func (csp *impl) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (valid bool, err error) {