-
Notifications
You must be signed in to change notification settings - Fork 1
/
impl.go
372 lines (316 loc) · 9.98 KB
/
impl.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package main
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(config map[string]interface{}) (string, error) {
keyStorePath, ok := config["keyStore"]
viperconfig := viper.New()
viperconfig.AutomaticEnv()
replacer := strings.NewReplacer(".", "_")
viperconfig.SetEnvKeyReplacer(replacer)
if !ok {
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 "", fmt.Errorf("You need to specify the plugin key store!")
}
}
return keyStorePath.(string), nil
}
// New returns a new instance of the BCCSP implementation
func New(config map[string]interface{}) (bccsp.BCCSP, error) {
var (
swCsp bccsp.BCCSP
ks bccsp.KeyStore
err error
)
keyStorePath, err := getKeyStoreDir(config)
if err != nil {
return nil, err
}
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) {
switch k := k.(type) {
case *sm2PrivateKey:
return verifySM2(&(k.privKey.PublicKey), signature, digest, opts)
case *sm2PublicKey:
return verifySM2(k.pubKey, signature, digest, opts)
default:
return csp.sw.Verify(k, signature, digest, opts)
}
}
// Encrypt encrypts plaintext using key k.
// The opts argument should be appropriate for the algorithm used.
func (csp *impl) Encrypt(k bccsp.Key, plaintext []byte, opts bccsp.EncrypterOpts) (ciphertext []byte, err error) {
return nil, nil
}
// Decrypt decrypts ciphertext using key k.
// The opts argument should be appropriate for the algorithm used.
func (csp *impl) Decrypt(k bccsp.Key, ciphertext []byte, opts bccsp.DecrypterOpts) (plaintext []byte, err error) {
return nil, nil
}