github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/bccsp/sw/keygen.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  
    17  package sw
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"crypto/elliptic"
    22  	"crypto/rand"
    23  	"crypto/rsa"
    24  	"fmt"
    25  
    26  	"github.com/hyperledger/fabric/bccsp"
    27  )
    28  
    29  type ecdsaKeyGenerator struct {
    30  	curve elliptic.Curve
    31  }
    32  
    33  func (kg *ecdsaKeyGenerator) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) {
    34  	privKey, err := ecdsa.GenerateKey(kg.curve, rand.Reader)
    35  	if err != nil {
    36  		return nil, fmt.Errorf("Failed generating ECDSA key for [%v]: [%s]", kg.curve, err)
    37  	}
    38  
    39  	return &ecdsaPrivateKey{privKey}, nil
    40  }
    41  
    42  type aesKeyGenerator struct {
    43  	length int
    44  }
    45  
    46  func (kg *aesKeyGenerator) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) {
    47  	lowLevelKey, err := GetRandomBytes(int(kg.length))
    48  	if err != nil {
    49  		return nil, fmt.Errorf("Failed generating AES %d key [%s]", kg.length, err)
    50  	}
    51  
    52  	return &aesPrivateKey{lowLevelKey, false}, nil
    53  }
    54  
    55  type rsaKeyGenerator struct {
    56  	length int
    57  }
    58  
    59  func (kg *rsaKeyGenerator) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) {
    60  	lowLevelKey, err := rsa.GenerateKey(rand.Reader, int(kg.length))
    61  
    62  	if err != nil {
    63  		return nil, fmt.Errorf("Failed generating RSA %d key [%s]", kg.length, err)
    64  	}
    65  
    66  	return &rsaPrivateKey{lowLevelKey}, nil
    67  }