github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/bccsp/sw/impl.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 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 sw
    17  
    18  import (
    19  	"crypto/elliptic"
    20  	"crypto/sha256"
    21  	"crypto/sha512"
    22  	"hash"
    23  	"reflect"
    24  
    25  	"github.com/hyperledger/fabric/bccsp"
    26  	"github.com/hyperledger/fabric/common/errors"
    27  	"github.com/hyperledger/fabric/common/flogging"
    28  	"golang.org/x/crypto/sha3"
    29  )
    30  
    31  var (
    32  	logger = flogging.MustGetLogger("bccsp_sw")
    33  )
    34  
    35  // NewDefaultSecurityLevel returns a new instance of the software-based BCCSP
    36  // at security level 256, hash family SHA2 and using FolderBasedKeyStore as KeyStore.
    37  func NewDefaultSecurityLevel(keyStorePath string) (bccsp.BCCSP, error) {
    38  	ks := &fileBasedKeyStore{}
    39  	if err := ks.Init(nil, keyStorePath, false); err != nil {
    40  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed initializing key store at [%v]", keyStorePath).WrapError(err)
    41  	}
    42  
    43  	return New(256, "SHA2", ks)
    44  }
    45  
    46  // NewDefaultSecurityLevel returns a new instance of the software-based BCCSP
    47  // at security level 256, hash family SHA2 and using the passed KeyStore.
    48  func NewDefaultSecurityLevelWithKeystore(keyStore bccsp.KeyStore) (bccsp.BCCSP, error) {
    49  	return New(256, "SHA2", keyStore)
    50  }
    51  
    52  // New returns a new instance of the software-based BCCSP
    53  // set at the passed security level, hash family and KeyStore.
    54  func New(securityLevel int, hashFamily string, keyStore bccsp.KeyStore) (bccsp.BCCSP, error) {
    55  	// Init config
    56  	conf := &config{}
    57  	err := conf.setSecurityLevel(securityLevel, hashFamily)
    58  	if err != nil {
    59  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed initializing configuration at [%v,%v]", securityLevel, hashFamily).WrapError(err)
    60  	}
    61  
    62  	// Check KeyStore
    63  	if keyStore == nil {
    64  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid bccsp.KeyStore instance. It must be different from nil.")
    65  	}
    66  
    67  	// Set the encryptors
    68  	encryptors := make(map[reflect.Type]Encryptor)
    69  	encryptors[reflect.TypeOf(&aesPrivateKey{})] = &aescbcpkcs7Encryptor{}
    70  
    71  	// Set the decryptors
    72  	decryptors := make(map[reflect.Type]Decryptor)
    73  	decryptors[reflect.TypeOf(&aesPrivateKey{})] = &aescbcpkcs7Decryptor{}
    74  
    75  	// Set the signers
    76  	signers := make(map[reflect.Type]Signer)
    77  	signers[reflect.TypeOf(&ecdsaPrivateKey{})] = &ecdsaSigner{}
    78  	signers[reflect.TypeOf(&rsaPrivateKey{})] = &rsaSigner{}
    79  
    80  	// Set the verifiers
    81  	verifiers := make(map[reflect.Type]Verifier)
    82  	verifiers[reflect.TypeOf(&ecdsaPrivateKey{})] = &ecdsaPrivateKeyVerifier{}
    83  	verifiers[reflect.TypeOf(&ecdsaPublicKey{})] = &ecdsaPublicKeyKeyVerifier{}
    84  	verifiers[reflect.TypeOf(&rsaPrivateKey{})] = &rsaPrivateKeyVerifier{}
    85  	verifiers[reflect.TypeOf(&rsaPublicKey{})] = &rsaPublicKeyKeyVerifier{}
    86  
    87  	// Set the hashers
    88  	hashers := make(map[reflect.Type]Hasher)
    89  	hashers[reflect.TypeOf(&bccsp.SHAOpts{})] = &hasher{hash: conf.hashFunction}
    90  	hashers[reflect.TypeOf(&bccsp.SHA256Opts{})] = &hasher{hash: sha256.New}
    91  	hashers[reflect.TypeOf(&bccsp.SHA384Opts{})] = &hasher{hash: sha512.New384}
    92  	hashers[reflect.TypeOf(&bccsp.SHA3_256Opts{})] = &hasher{hash: sha3.New256}
    93  	hashers[reflect.TypeOf(&bccsp.SHA3_384Opts{})] = &hasher{hash: sha3.New384}
    94  
    95  	impl := &impl{
    96  		conf:       conf,
    97  		ks:         keyStore,
    98  		encryptors: encryptors,
    99  		decryptors: decryptors,
   100  		signers:    signers,
   101  		verifiers:  verifiers,
   102  		hashers:    hashers}
   103  
   104  	// Set the key generators
   105  	keyGenerators := make(map[reflect.Type]KeyGenerator)
   106  	keyGenerators[reflect.TypeOf(&bccsp.ECDSAKeyGenOpts{})] = &ecdsaKeyGenerator{curve: conf.ellipticCurve}
   107  	keyGenerators[reflect.TypeOf(&bccsp.ECDSAP256KeyGenOpts{})] = &ecdsaKeyGenerator{curve: elliptic.P256()}
   108  	keyGenerators[reflect.TypeOf(&bccsp.ECDSAP384KeyGenOpts{})] = &ecdsaKeyGenerator{curve: elliptic.P384()}
   109  	keyGenerators[reflect.TypeOf(&bccsp.AESKeyGenOpts{})] = &aesKeyGenerator{length: conf.aesBitLength}
   110  	keyGenerators[reflect.TypeOf(&bccsp.AES256KeyGenOpts{})] = &aesKeyGenerator{length: 32}
   111  	keyGenerators[reflect.TypeOf(&bccsp.AES192KeyGenOpts{})] = &aesKeyGenerator{length: 24}
   112  	keyGenerators[reflect.TypeOf(&bccsp.AES128KeyGenOpts{})] = &aesKeyGenerator{length: 16}
   113  	keyGenerators[reflect.TypeOf(&bccsp.RSAKeyGenOpts{})] = &rsaKeyGenerator{length: conf.rsaBitLength}
   114  	keyGenerators[reflect.TypeOf(&bccsp.RSA1024KeyGenOpts{})] = &rsaKeyGenerator{length: 1024}
   115  	keyGenerators[reflect.TypeOf(&bccsp.RSA2048KeyGenOpts{})] = &rsaKeyGenerator{length: 2048}
   116  	keyGenerators[reflect.TypeOf(&bccsp.RSA3072KeyGenOpts{})] = &rsaKeyGenerator{length: 3072}
   117  	keyGenerators[reflect.TypeOf(&bccsp.RSA4096KeyGenOpts{})] = &rsaKeyGenerator{length: 4096}
   118  	impl.keyGenerators = keyGenerators
   119  
   120  	// Set the key generators
   121  	keyDerivers := make(map[reflect.Type]KeyDeriver)
   122  	keyDerivers[reflect.TypeOf(&ecdsaPrivateKey{})] = &ecdsaPrivateKeyKeyDeriver{}
   123  	keyDerivers[reflect.TypeOf(&ecdsaPublicKey{})] = &ecdsaPublicKeyKeyDeriver{}
   124  	keyDerivers[reflect.TypeOf(&aesPrivateKey{})] = &aesPrivateKeyKeyDeriver{bccsp: impl}
   125  	impl.keyDerivers = keyDerivers
   126  
   127  	// Set the key importers
   128  	keyImporters := make(map[reflect.Type]KeyImporter)
   129  	keyImporters[reflect.TypeOf(&bccsp.AES256ImportKeyOpts{})] = &aes256ImportKeyOptsKeyImporter{}
   130  	keyImporters[reflect.TypeOf(&bccsp.HMACImportKeyOpts{})] = &hmacImportKeyOptsKeyImporter{}
   131  	keyImporters[reflect.TypeOf(&bccsp.ECDSAPKIXPublicKeyImportOpts{})] = &ecdsaPKIXPublicKeyImportOptsKeyImporter{}
   132  	keyImporters[reflect.TypeOf(&bccsp.ECDSAPrivateKeyImportOpts{})] = &ecdsaPrivateKeyImportOptsKeyImporter{}
   133  	keyImporters[reflect.TypeOf(&bccsp.ECDSAGoPublicKeyImportOpts{})] = &ecdsaGoPublicKeyImportOptsKeyImporter{}
   134  	keyImporters[reflect.TypeOf(&bccsp.RSAGoPublicKeyImportOpts{})] = &rsaGoPublicKeyImportOptsKeyImporter{}
   135  	keyImporters[reflect.TypeOf(&bccsp.X509PublicKeyImportOpts{})] = &x509PublicKeyImportOptsKeyImporter{bccsp: impl}
   136  
   137  	impl.keyImporters = keyImporters
   138  
   139  	return impl, nil
   140  }
   141  
   142  // SoftwareBasedBCCSP is the software-based implementation of the BCCSP.
   143  type impl struct {
   144  	conf *config
   145  	ks   bccsp.KeyStore
   146  
   147  	keyGenerators map[reflect.Type]KeyGenerator
   148  	keyDerivers   map[reflect.Type]KeyDeriver
   149  	keyImporters  map[reflect.Type]KeyImporter
   150  	encryptors    map[reflect.Type]Encryptor
   151  	decryptors    map[reflect.Type]Decryptor
   152  	signers       map[reflect.Type]Signer
   153  	verifiers     map[reflect.Type]Verifier
   154  	hashers       map[reflect.Type]Hasher
   155  }
   156  
   157  // KeyGen generates a key using opts.
   158  func (csp *impl) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) {
   159  	// Validate arguments
   160  	if opts == nil {
   161  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid Opts parameter. It must not be nil.")
   162  	}
   163  
   164  	keyGenerator, found := csp.keyGenerators[reflect.TypeOf(opts)]
   165  	if !found {
   166  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.NotFound, "Unsupported 'KeyGenOpts' provided [%v]", opts)
   167  	}
   168  
   169  	k, err = keyGenerator.KeyGen(opts)
   170  	if err != nil {
   171  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed generating key with opts [%v]", opts).WrapError(err)
   172  	}
   173  
   174  	// If the key is not Ephemeral, store it.
   175  	if !opts.Ephemeral() {
   176  		// Store the key
   177  		err = csp.ks.StoreKey(k)
   178  		if err != nil {
   179  			return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed storing key [%s]. [%s]", opts.Algorithm(), err)
   180  		}
   181  	}
   182  
   183  	return k, nil
   184  }
   185  
   186  // KeyDeriv derives a key from k using opts.
   187  // The opts argument should be appropriate for the primitive used.
   188  func (csp *impl) KeyDeriv(k bccsp.Key, opts bccsp.KeyDerivOpts) (dk bccsp.Key, err error) {
   189  	// Validate arguments
   190  	if k == nil {
   191  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid Key. It must not be nil.")
   192  	}
   193  	if opts == nil {
   194  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid opts. It must not be nil.")
   195  	}
   196  
   197  	keyDeriver, found := csp.keyDerivers[reflect.TypeOf(k)]
   198  	if !found {
   199  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.NotFound, "Unsupported 'Key' provided [%v]", k)
   200  	}
   201  
   202  	k, err = keyDeriver.KeyDeriv(k, opts)
   203  	if err != nil {
   204  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed deriving key with opts [%v]", opts).WrapError(err)
   205  	}
   206  
   207  	// If the key is not Ephemeral, store it.
   208  	if !opts.Ephemeral() {
   209  		// Store the key
   210  		err = csp.ks.StoreKey(k)
   211  		if err != nil {
   212  			return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed storing key [%s]. [%s]", opts.Algorithm(), err)
   213  		}
   214  	}
   215  
   216  	return k, nil
   217  }
   218  
   219  // KeyImport imports a key from its raw representation using opts.
   220  // The opts argument should be appropriate for the primitive used.
   221  func (csp *impl) KeyImport(raw interface{}, opts bccsp.KeyImportOpts) (k bccsp.Key, err error) {
   222  	// Validate arguments
   223  	if raw == nil {
   224  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid raw. It must not be nil.")
   225  	}
   226  	if opts == nil {
   227  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid opts. It must not be nil.")
   228  	}
   229  
   230  	keyImporter, found := csp.keyImporters[reflect.TypeOf(opts)]
   231  	if !found {
   232  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.NotFound, "Unsupported 'KeyImportOpts' provided [%v]", opts)
   233  	}
   234  
   235  	k, err = keyImporter.KeyImport(raw, opts)
   236  	if err != nil {
   237  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed importing key with opts [%v]", opts).WrapError(err)
   238  	}
   239  
   240  	// If the key is not Ephemeral, store it.
   241  	if !opts.Ephemeral() {
   242  		// Store the key
   243  		err = csp.ks.StoreKey(k)
   244  		if err != nil {
   245  			return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed storing imported key with opts [%v]", opts).WrapError(err)
   246  		}
   247  	}
   248  
   249  	return
   250  }
   251  
   252  // GetKey returns the key this CSP associates to
   253  // the Subject Key Identifier ski.
   254  func (csp *impl) GetKey(ski []byte) (k bccsp.Key, err error) {
   255  	k, err = csp.ks.GetKey(ski)
   256  	if err != nil {
   257  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed getting key for SKI [%v]", ski).WrapError(err)
   258  	}
   259  
   260  	return
   261  }
   262  
   263  // Hash hashes messages msg using options opts.
   264  func (csp *impl) Hash(msg []byte, opts bccsp.HashOpts) (digest []byte, err error) {
   265  	// Validate arguments
   266  	if opts == nil {
   267  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid opts. It must not be nil.")
   268  	}
   269  
   270  	hasher, found := csp.hashers[reflect.TypeOf(opts)]
   271  	if !found {
   272  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.NotFound, "Unsupported 'HashOpt' provided [%v]", opts)
   273  	}
   274  
   275  	digest, err = hasher.Hash(msg, opts)
   276  	if err != nil {
   277  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed hashing with opts [%v]", opts).WrapError(err)
   278  	}
   279  
   280  	return
   281  }
   282  
   283  // GetHash returns and instance of hash.Hash using options opts.
   284  // If opts is nil then the default hash function is returned.
   285  func (csp *impl) GetHash(opts bccsp.HashOpts) (h hash.Hash, err error) {
   286  	// Validate arguments
   287  	if opts == nil {
   288  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid opts. It must not be nil.")
   289  	}
   290  
   291  	hasher, found := csp.hashers[reflect.TypeOf(opts)]
   292  	if !found {
   293  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.NotFound, "Unsupported 'HashOpt' provided [%v]", opts)
   294  	}
   295  
   296  	h, err = hasher.GetHash(opts)
   297  	if err != nil {
   298  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed getting hash function with opts [%v]", opts).WrapError(err)
   299  	}
   300  
   301  	return
   302  }
   303  
   304  // Sign signs digest using key k.
   305  // The opts argument should be appropriate for the primitive used.
   306  //
   307  // Note that when a signature of a hash of a larger message is needed,
   308  // the caller is responsible for hashing the larger message and passing
   309  // the hash (as digest).
   310  func (csp *impl) Sign(k bccsp.Key, digest []byte, opts bccsp.SignerOpts) (signature []byte, err error) {
   311  	// Validate arguments
   312  	if k == nil {
   313  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid Key. It must not be nil.")
   314  	}
   315  	if len(digest) == 0 {
   316  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid digest. Cannot be empty.")
   317  	}
   318  
   319  	signer, found := csp.signers[reflect.TypeOf(k)]
   320  	if !found {
   321  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.NotFound, "Unsupported 'SignKey' provided [%v]", k)
   322  	}
   323  
   324  	signature, err = signer.Sign(k, digest, opts)
   325  	if err != nil {
   326  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed signing with opts [%v]", opts).WrapError(err)
   327  	}
   328  
   329  	return
   330  }
   331  
   332  // Verify verifies signature against key k and digest
   333  func (csp *impl) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (valid bool, err error) {
   334  	// Validate arguments
   335  	if k == nil {
   336  		return false, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid Key. It must not be nil.")
   337  	}
   338  	if len(signature) == 0 {
   339  		return false, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid signature. Cannot be empty.")
   340  	}
   341  	if len(digest) == 0 {
   342  		return false, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid digest. Cannot be empty.")
   343  	}
   344  
   345  	verifier, found := csp.verifiers[reflect.TypeOf(k)]
   346  	if !found {
   347  		return false, errors.ErrorWithCallstack(errors.BCCSP, errors.NotFound, "Unsupported 'VerifyKey' provided [%v]", k)
   348  	}
   349  
   350  	valid, err = verifier.Verify(k, signature, digest, opts)
   351  	if err != nil {
   352  		return false, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed verifing with opts [%v]", opts).WrapError(err)
   353  	}
   354  
   355  	return
   356  }
   357  
   358  // Encrypt encrypts plaintext using key k.
   359  // The opts argument should be appropriate for the primitive used.
   360  func (csp *impl) Encrypt(k bccsp.Key, plaintext []byte, opts bccsp.EncrypterOpts) (ciphertext []byte, err error) {
   361  	// Validate arguments
   362  	if k == nil {
   363  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid Key. It must not be nil.")
   364  	}
   365  
   366  	encryptor, found := csp.encryptors[reflect.TypeOf(k)]
   367  	if !found {
   368  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.NotFound, "Unsupported 'EncryptKey' provided [%v]", k)
   369  	}
   370  
   371  	return encryptor.Encrypt(k, plaintext, opts)
   372  }
   373  
   374  // Decrypt decrypts ciphertext using key k.
   375  // The opts argument should be appropriate for the primitive used.
   376  func (csp *impl) Decrypt(k bccsp.Key, ciphertext []byte, opts bccsp.DecrypterOpts) (plaintext []byte, err error) {
   377  	// Validate arguments
   378  	if k == nil {
   379  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.BadRequest, "Invalid Key. It must not be nil.")
   380  	}
   381  
   382  	decryptor, found := csp.decryptors[reflect.TypeOf(k)]
   383  	if !found {
   384  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.NotFound, "Unsupported 'DecryptKey' provided [%v]", k)
   385  	}
   386  
   387  	plaintext, err = decryptor.Decrypt(k, ciphertext, opts)
   388  	if err != nil {
   389  		return nil, errors.ErrorWithCallstack(errors.BCCSP, errors.Internal, "Failed decrypting with opts [%v]", opts).WrapError(err)
   390  	}
   391  
   392  	return
   393  }