github.com/kaituanwang/hyperledger@v2.0.1+incompatible/bccsp/sw/ecdsa.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/ecdsa"
    20  	"crypto/rand"
    21  	"fmt"
    22  
    23  	"github.com/hyperledger/fabric/bccsp"
    24  	"github.com/hyperledger/fabric/bccsp/utils"
    25  )
    26  
    27  func signECDSA(k *ecdsa.PrivateKey, digest []byte, opts bccsp.SignerOpts) ([]byte, error) {
    28  	r, s, err := ecdsa.Sign(rand.Reader, k, digest)
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  
    33  	s, _, err = utils.ToLowS(&k.PublicKey, s)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  
    38  	return utils.MarshalECDSASignature(r, s)
    39  }
    40  
    41  func verifyECDSA(k *ecdsa.PublicKey, signature, digest []byte, opts bccsp.SignerOpts) (bool, error) {
    42  	r, s, err := utils.UnmarshalECDSASignature(signature)
    43  	if err != nil {
    44  		return false, fmt.Errorf("Failed unmashalling signature [%s]", err)
    45  	}
    46  
    47  	lowS, err := utils.IsLowS(k, s)
    48  	if err != nil {
    49  		return false, err
    50  	}
    51  
    52  	if !lowS {
    53  		return false, fmt.Errorf("Invalid S. Must be smaller than half the order [%s][%s].", s, utils.GetCurveHalfOrdersAt(k.Curve))
    54  	}
    55  
    56  	return ecdsa.Verify(k, digest, r, s), nil
    57  }
    58  
    59  type ecdsaSigner struct{}
    60  
    61  func (s *ecdsaSigner) Sign(k bccsp.Key, digest []byte, opts bccsp.SignerOpts) ([]byte, error) {
    62  	return signECDSA(k.(*ecdsaPrivateKey).privKey, digest, opts)
    63  }
    64  
    65  type ecdsaPrivateKeyVerifier struct{}
    66  
    67  func (v *ecdsaPrivateKeyVerifier) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (bool, error) {
    68  	return verifyECDSA(&(k.(*ecdsaPrivateKey).privKey.PublicKey), signature, digest, opts)
    69  }
    70  
    71  type ecdsaPublicKeyKeyVerifier struct{}
    72  
    73  func (v *ecdsaPublicKeyKeyVerifier) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (bool, error) {
    74  	return verifyECDSA(k.(*ecdsaPublicKey).pubKey, signature, digest, opts)
    75  }