github.com/lzy4123/fabric@v2.1.1+incompatible/bccsp/idemix/handlers/user.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 package handlers 7 8 import ( 9 "crypto/sha256" 10 11 "github.com/hyperledger/fabric/bccsp" 12 "github.com/pkg/errors" 13 ) 14 15 // userSecretKey contains the User secret key 16 type userSecretKey struct { 17 // sk is the idemix reference to the User key 18 sk Big 19 // Exportable if true, sk can be exported via the Bytes function 20 exportable bool 21 } 22 23 func NewUserSecretKey(sk Big, exportable bool) *userSecretKey { 24 return &userSecretKey{sk: sk, exportable: exportable} 25 } 26 27 func (k *userSecretKey) Bytes() ([]byte, error) { 28 if k.exportable { 29 return k.sk.Bytes() 30 } 31 32 return nil, errors.New("not exportable") 33 } 34 35 func (k *userSecretKey) SKI() []byte { 36 raw, err := k.sk.Bytes() 37 if err != nil { 38 return nil 39 } 40 hash := sha256.New() 41 hash.Write(raw) 42 return hash.Sum(nil) 43 } 44 45 func (*userSecretKey) Symmetric() bool { 46 return true 47 } 48 49 func (*userSecretKey) Private() bool { 50 return true 51 } 52 53 func (k *userSecretKey) PublicKey() (bccsp.Key, error) { 54 return nil, errors.New("cannot call this method on a symmetric key") 55 } 56 57 type UserKeyGen struct { 58 // Exportable is a flag to allow an issuer secret key to be marked as Exportable. 59 // If a secret key is marked as Exportable, its Bytes method will return the key's byte representation. 60 Exportable bool 61 // User implements the underlying cryptographic algorithms 62 User User 63 } 64 65 func (g *UserKeyGen) KeyGen(opts bccsp.KeyGenOpts) (bccsp.Key, error) { 66 sk, err := g.User.NewKey() 67 if err != nil { 68 return nil, err 69 } 70 71 return &userSecretKey{exportable: g.Exportable, sk: sk}, nil 72 } 73 74 // UserKeyImporter import user keys 75 type UserKeyImporter struct { 76 // Exportable is a flag to allow a secret key to be marked as Exportable. 77 // If a secret key is marked as Exportable, its Bytes method will return the key's byte representation. 78 Exportable bool 79 // User implements the underlying cryptographic algorithms 80 User User 81 } 82 83 func (i *UserKeyImporter) KeyImport(raw interface{}, opts bccsp.KeyImportOpts) (k bccsp.Key, err error) { 84 der, ok := raw.([]byte) 85 if !ok { 86 return nil, errors.New("invalid raw, expected byte array") 87 } 88 89 if len(der) == 0 { 90 return nil, errors.New("invalid raw, it must not be nil") 91 } 92 93 sk, err := i.User.NewKeyFromBytes(raw.([]byte)) 94 if err != nil { 95 return nil, err 96 } 97 98 return &userSecretKey{exportable: i.Exportable, sk: sk}, nil 99 }