github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/common/tools/cryptogen/csp/csp.go (about) 1 /* 2 Copyright IBM Corp. 2017 All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 package csp 17 18 import ( 19 "crypto" 20 "crypto/ecdsa" 21 "crypto/x509" 22 23 "github.com/hyperledger/fabric/bccsp" 24 "github.com/hyperledger/fabric/bccsp/factory" 25 "github.com/hyperledger/fabric/bccsp/signer" 26 "github.com/hyperledger/fabric/bccsp/sw" 27 ) 28 29 // GeneratePrivateKey creates a private key and stores it in keystorePath 30 func GeneratePrivateKey(keystorePath string) (bccsp.Key, 31 crypto.Signer, error) { 32 33 csp := factory.GetDefault() 34 var response error 35 var priv bccsp.Key 36 signer := &signer.CryptoSigner{} 37 38 // generate a key 39 priv, err := csp.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: true}) 40 response = err 41 if err == nil { 42 // write it to the keystore 43 ks, err := sw.NewFileBasedKeyStore(nil, keystorePath, false) 44 response = err 45 if err == nil { 46 err = ks.StoreKey(priv) 47 response = err 48 if err == nil { 49 // create a crypto.Signer 50 err = signer.Init(csp, priv) 51 } 52 } 53 } 54 return priv, signer, response 55 56 } 57 58 func GetECPublicKey(priv bccsp.Key) (*ecdsa.PublicKey, error) { 59 60 // get the public key 61 pubKey, err := priv.PublicKey() 62 if err != nil { 63 return nil, err 64 } 65 // marshal to bytes 66 pubKeyBytes, err := pubKey.Bytes() 67 if err != nil { 68 return nil, err 69 } 70 // unmarshal using pkix 71 ecPubKey, err := x509.ParsePKIXPublicKey(pubKeyBytes) 72 if err != nil { 73 return nil, err 74 } 75 return ecPubKey.(*ecdsa.PublicKey), nil 76 }