-
Notifications
You must be signed in to change notification settings - Fork 42
/
inmemoryks.go
68 lines (53 loc) · 1.38 KB
/
inmemoryks.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package sw
import (
"encoding/hex"
"sync"
"github.com/VoneChain-CS/fabric-gm/bccsp"
"github.com/pkg/errors"
)
// NewInMemoryKeyStore instantiates an ephemeral in-memory keystore
func NewInMemoryKeyStore() bccsp.KeyStore {
eks := &inmemoryKeyStore{}
eks.keys = make(map[string]bccsp.Key)
return eks
}
type inmemoryKeyStore struct {
// keys maps the hex-encoded SKI to keys
keys map[string]bccsp.Key
m sync.RWMutex
}
// ReadOnly returns false - the key store is not read-only
func (ks *inmemoryKeyStore) ReadOnly() bool {
return false
}
// GetKey returns a key object whose SKI is the one passed.
func (ks *inmemoryKeyStore) GetKey(ski []byte) (bccsp.Key, error) {
if len(ski) == 0 {
return nil, errors.New("ski is nil or empty")
}
skiStr := hex.EncodeToString(ski)
ks.m.RLock()
defer ks.m.RUnlock()
if key, found := ks.keys[skiStr]; found {
return key, nil
}
return nil, errors.Errorf("no key found for ski %x", ski)
}
// StoreKey stores the key k in this KeyStore.
func (ks *inmemoryKeyStore) StoreKey(k bccsp.Key) error {
if k == nil {
return errors.New("key is nil")
}
ski := hex.EncodeToString(k.SKI())
ks.m.Lock()
defer ks.m.Unlock()
if _, found := ks.keys[ski]; found {
return errors.Errorf("ski %x already exists in the keystore", k.SKI())
}
ks.keys[ski] = k
return nil
}