github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/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/elliptic"
    21  	"crypto/rand"
    22  	"encoding/asn1"
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  
    27  	"github.com/hyperledger/fabric/bccsp"
    28  )
    29  
    30  type ecdsaSignature struct {
    31  	R, S *big.Int
    32  }
    33  
    34  var (
    35  	// curveHalfOrders contains the precomputed curve group orders halved.
    36  	// It is used to ensure that signature' S value is lower or equal to the
    37  	// curve group order halved. We accept only low-S signatures.
    38  	// They are precomputed for efficiency reasons.
    39  	curveHalfOrders map[elliptic.Curve]*big.Int = map[elliptic.Curve]*big.Int{
    40  		elliptic.P224(): new(big.Int).Rsh(elliptic.P224().Params().N, 1),
    41  		elliptic.P256(): new(big.Int).Rsh(elliptic.P256().Params().N, 1),
    42  		elliptic.P384(): new(big.Int).Rsh(elliptic.P384().Params().N, 1),
    43  		elliptic.P521(): new(big.Int).Rsh(elliptic.P521().Params().N, 1),
    44  	}
    45  )
    46  
    47  func marshalECDSASignature(r, s *big.Int) ([]byte, error) {
    48  	return asn1.Marshal(ecdsaSignature{r, s})
    49  }
    50  
    51  func unmarshalECDSASignature(raw []byte) (*big.Int, *big.Int, error) {
    52  	// Unmarshal
    53  	sig := new(ecdsaSignature)
    54  	_, err := asn1.Unmarshal(raw, sig)
    55  	if err != nil {
    56  		return nil, nil, fmt.Errorf("Failed unmashalling signature [%s]", err)
    57  	}
    58  
    59  	// Validate sig
    60  	if sig.R == nil {
    61  		return nil, nil, errors.New("Invalid signature. R must be different from nil.")
    62  	}
    63  	if sig.S == nil {
    64  		return nil, nil, errors.New("Invalid signature. S must be different from nil.")
    65  	}
    66  
    67  	if sig.R.Sign() != 1 {
    68  		return nil, nil, errors.New("Invalid signature. R must be larger than zero")
    69  	}
    70  	if sig.S.Sign() != 1 {
    71  		return nil, nil, errors.New("Invalid signature. S must be larger than zero")
    72  	}
    73  
    74  	return sig.R, sig.S, nil
    75  }
    76  
    77  func (csp *impl) signECDSA(k *ecdsa.PrivateKey, digest []byte, opts bccsp.SignerOpts) (signature []byte, err error) {
    78  	r, s, err := ecdsa.Sign(rand.Reader, k, digest)
    79  	if err != nil {
    80  		return nil, err
    81  	}
    82  
    83  	// check for low-S
    84  	halfOrder, ok := curveHalfOrders[k.Curve]
    85  	if !ok {
    86  		return nil, fmt.Errorf("Curve not recognized [%s]", k.Curve)
    87  	}
    88  
    89  	// is s > halfOrder Then
    90  	if s.Cmp(halfOrder) == 1 {
    91  		// Set s to N - s that will be then in the lower part of signature space
    92  		// less or equal to half order
    93  		s.Sub(k.Params().N, s)
    94  	}
    95  
    96  	return marshalECDSASignature(r, s)
    97  }
    98  
    99  func (csp *impl) verifyECDSA(k *ecdsa.PublicKey, signature, digest []byte, opts bccsp.SignerOpts) (valid bool, err error) {
   100  	r, s, err := unmarshalECDSASignature(signature)
   101  	if err != nil {
   102  		return false, fmt.Errorf("Failed unmashalling signature [%s]", err)
   103  	}
   104  
   105  	// check for low-S
   106  	halfOrder, ok := curveHalfOrders[k.Curve]
   107  	if !ok {
   108  		return false, fmt.Errorf("Curve not recognized [%s]", k.Curve)
   109  	}
   110  
   111  	// If s > halfOrder Then
   112  	if s.Cmp(halfOrder) == 1 {
   113  		return false, fmt.Errorf("Invalid S. Must be smaller than half the order [%s][%s].", s, halfOrder)
   114  	}
   115  
   116  	return ecdsa.Verify(k, digest, r, s), nil
   117  }