github.com/lzy4123/fabric@v2.1.1+incompatible/bccsp/signer/signer.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package signer
     8  
     9  import (
    10  	"crypto"
    11  	"io"
    12  
    13  	"github.com/hyperledger/fabric/bccsp"
    14  	"github.com/hyperledger/fabric/bccsp/utils"
    15  	"github.com/pkg/errors"
    16  )
    17  
    18  // bccspCryptoSigner is the BCCSP-based implementation of a crypto.Signer
    19  type bccspCryptoSigner struct {
    20  	csp bccsp.BCCSP
    21  	key bccsp.Key
    22  	pk  interface{}
    23  }
    24  
    25  // New returns a new BCCSP-based crypto.Signer
    26  // for the given BCCSP instance and key.
    27  func New(csp bccsp.BCCSP, key bccsp.Key) (crypto.Signer, error) {
    28  	// Validate arguments
    29  	if csp == nil {
    30  		return nil, errors.New("bccsp instance must be different from nil.")
    31  	}
    32  	if key == nil {
    33  		return nil, errors.New("key must be different from nil.")
    34  	}
    35  	if key.Symmetric() {
    36  		return nil, errors.New("key must be asymmetric.")
    37  	}
    38  
    39  	// Marshall the bccsp public key as a crypto.PublicKey
    40  	pub, err := key.PublicKey()
    41  	if err != nil {
    42  		return nil, errors.Wrap(err, "failed getting public key")
    43  	}
    44  
    45  	raw, err := pub.Bytes()
    46  	if err != nil {
    47  		return nil, errors.Wrap(err, "failed marshalling public key")
    48  	}
    49  
    50  	pk, err := utils.DERToPublicKey(raw)
    51  	if err != nil {
    52  		return nil, errors.Wrap(err, "failed marshalling der to public key")
    53  	}
    54  
    55  	return &bccspCryptoSigner{csp, key, pk}, nil
    56  }
    57  
    58  // Public returns the public key corresponding to the opaque,
    59  // private key.
    60  func (s *bccspCryptoSigner) Public() crypto.PublicKey {
    61  	return s.pk
    62  }
    63  
    64  // Sign signs digest with the private key, possibly using entropy from rand.
    65  // For an (EC)DSA key, it should be a DER-serialised, ASN.1 signature
    66  // structure.
    67  //
    68  // Hash implements the SignerOpts interface and, in most cases, one can
    69  // simply pass in the hash function used as opts. Sign may also attempt
    70  // to type assert opts to other types in order to obtain algorithm
    71  // specific values. See the documentation in each package for details.
    72  //
    73  // Note that when a signature of a hash of a larger message is needed,
    74  // the caller is responsible for hashing the larger message and passing
    75  // the hash (as digest) and the hash function (as opts) to Sign.
    76  func (s *bccspCryptoSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
    77  	return s.csp.Sign(s.key, digest, opts)
    78  }