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

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package pkcs11
     8  
     9  import (
    10  	"crypto/ecdsa"
    11  	"fmt"
    12  
    13  	"github.com/hyperledger/fabric/bccsp"
    14  	"github.com/hyperledger/fabric/bccsp/utils"
    15  )
    16  
    17  func (csp *impl) signECDSA(k ecdsaPrivateKey, digest []byte, opts bccsp.SignerOpts) ([]byte, error) {
    18  	r, s, err := csp.signP11ECDSA(k.ski, digest)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	s, err = utils.ToLowS(k.pub.pub, s)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	return utils.MarshalECDSASignature(r, s)
    29  }
    30  
    31  func (csp *impl) verifyECDSA(k ecdsaPublicKey, signature, digest []byte, opts bccsp.SignerOpts) (bool, error) {
    32  	r, s, err := utils.UnmarshalECDSASignature(signature)
    33  	if err != nil {
    34  		return false, fmt.Errorf("Failed unmashalling signature [%s]", err)
    35  	}
    36  
    37  	lowS, err := utils.IsLowS(k.pub, s)
    38  	if err != nil {
    39  		return false, err
    40  	}
    41  
    42  	if !lowS {
    43  		return false, fmt.Errorf("Invalid S. Must be smaller than half the order [%s][%s]", s, utils.GetCurveHalfOrdersAt(k.pub.Curve))
    44  	}
    45  
    46  	if csp.softVerify {
    47  		return ecdsa.Verify(k.pub, digest, r, s), nil
    48  	}
    49  	return csp.verifyP11ECDSA(k.ski, digest, r, s, k.pub.Curve.Params().BitSize/8)
    50  
    51  }