github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/security/crypto/rfc6979/ecdsa.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package rfc6979
    19  
    20  // From https://github.com/codahale/rfc6979
    21  
    22  import (
    23  	"crypto/ecdsa"
    24  	"crypto/elliptic"
    25  	"hash"
    26  	"math/big"
    27  )
    28  
    29  // SignECDSA signs an arbitrary length hash (which should be the result of
    30  // hashing a larger message) using the private key, priv. It returns the
    31  // signature as a pair of integers.
    32  //
    33  // Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated
    34  // to the byte-length of the subgroup. This function does not perform that
    35  // truncation itself.
    36  func SignECDSA(priv *ecdsa.PrivateKey, digest []byte, alg func() hash.Hash) (r, s *big.Int) {
    37  	c := priv.PublicKey.Curve
    38  	N := c.Params().N
    39  
    40  	generateSecret(N, priv.D, alg, digest, func(k *big.Int) bool {
    41  		inv := new(big.Int).ModInverse(k, N)
    42  		r, _ = priv.Curve.ScalarBaseMult(k.Bytes())
    43  		r.Mod(r, N)
    44  
    45  		if r.Sign() == 0 {
    46  			return false
    47  		}
    48  
    49  		e := hashToInt(digest, c)
    50  		s = new(big.Int).Mul(priv.D, r)
    51  		s.Add(s, e)
    52  		s.Mul(s, inv)
    53  		s.Mod(s, N)
    54  
    55  		return s.Sign() != 0
    56  	})
    57  
    58  	return
    59  }
    60  
    61  // copied from crypto/ecdsa.
    62  func hashToInt(digest []byte, c elliptic.Curve) *big.Int {
    63  	orderBits := c.Params().N.BitLen()
    64  	orderBytes := (orderBits + 7) / 8
    65  	if len(digest) > orderBytes {
    66  		digest = digest[:orderBytes]
    67  	}
    68  
    69  	ret := new(big.Int).SetBytes(digest)
    70  	excess := len(digest)*8 - orderBits
    71  	if excess > 0 {
    72  		ret.Rsh(ret, uint(excess))
    73  	}
    74  	return ret
    75  }