github.com/myafeier/fabric@v1.0.1-0.20170722181825-3a4b1f2bce86/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 ) 27 28 // GeneratePrivateKey creates a private key and stores it in keystorePath 29 func GeneratePrivateKey(keystorePath string) (bccsp.Key, 30 crypto.Signer, error) { 31 32 var err error 33 var priv bccsp.Key 34 var s crypto.Signer 35 36 opts := &factory.FactoryOpts{ 37 ProviderName: "SW", 38 SwOpts: &factory.SwOpts{ 39 HashFamily: "SHA2", 40 SecLevel: 256, 41 42 FileKeystore: &factory.FileKeystoreOpts{ 43 KeyStorePath: keystorePath, 44 }, 45 }, 46 } 47 csp, err := factory.GetBCCSPFromOpts(opts) 48 if err == nil { 49 // generate a key 50 priv, err = csp.KeyGen(&bccsp.ECDSAP256KeyGenOpts{Temporary: false}) 51 if err == nil { 52 // create a crypto.Signer 53 s, err = signer.New(csp, priv) 54 } 55 } 56 return priv, s, err 57 } 58 59 func GetECPublicKey(priv bccsp.Key) (*ecdsa.PublicKey, error) { 60 61 // get the public key 62 pubKey, err := priv.PublicKey() 63 if err != nil { 64 return nil, err 65 } 66 // marshal to bytes 67 pubKeyBytes, err := pubKey.Bytes() 68 if err != nil { 69 return nil, err 70 } 71 // unmarshal using pkix 72 ecPubKey, err := x509.ParsePKIXPublicKey(pubKeyBytes) 73 if err != nil { 74 return nil, err 75 } 76 return ecPubKey.(*ecdsa.PublicKey), nil 77 }