github.com/hellobchain/newcryptosm@v0.0.0-20221019060107-edb949a317e9/ecdsa/ecdsa.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as 6 // defined in FIPS 186-3. 7 // 8 // This implementation derives the nonce from an AES-CTR CSPRNG keyed by 9 // ChopMD(256, SHA2-512(priv.D || entropy || hash)). The CSPRNG key is IRO by 10 // a result of Coron; the AES-CTR stream is IRO under standard assumptions. 11 package ecdsa 12 13 // References: 14 // [NSA]: Suite B implementer's guide to FIPS 186-3, 15 // http://www.nsa.gov/ia/_files/ecdsa.pdf 16 // [SECG]: SECG, SEC1 17 // http://www.secg.org/sec1-v2.pdf 18 19 import ( 20 "crypto" 21 "crypto/aes" 22 "crypto/cipher" 23 "crypto/elliptic" 24 "crypto/sha512" 25 "encoding/asn1" 26 "errors" 27 "io" 28 "math/big" 29 ) 30 31 func IsSM2(params *elliptic.CurveParams) bool { 32 if params.Params().Name == "SM2" { 33 return true 34 } 35 return false 36 } 37 38 // A invertible implements fast inverse mod Curve.Params().N 39 type invertible interface { 40 // Inverse returns the inverse of k in GF(P) 41 Inverse(k *big.Int) *big.Int 42 } 43 44 // combinedMult implements fast multiplication S1*g + S2*p (g - generator, p - arbitrary point) 45 type combinedMult interface { 46 CombinedMult(bigX, bigY *big.Int, baseScalar, scalar []byte) (x, y *big.Int) 47 } 48 49 const ( 50 aesIV = "IV for ECDSA CTR" 51 ) 52 53 // PublicKey represents an ECDSA public key. 54 type PublicKey struct { 55 elliptic.Curve 56 X, Y *big.Int 57 } 58 59 // PrivateKey represents an ECDSA private key. 60 type PrivateKey struct { 61 PublicKey 62 D *big.Int 63 } 64 65 type ecdsaSignature struct { 66 R, S *big.Int 67 } 68 69 // Public returns the public key corresponding to priv. 70 func (priv *PrivateKey) Public() crypto.PublicKey { 71 return &priv.PublicKey 72 } 73 74 // Sign signs digest with priv, reading randomness from rand. The opts argument 75 // is not currently used but, in keeping with the crypto.Signer interface, 76 // should be the hash function used to digest the message. 77 // 78 // This method implements crypto.Signer, which is an interface to support keys 79 // where the private part is kept in, for example, a hardware module. Common 80 // uses should use the Sign function in this package directly. 81 func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { 82 r, s, err := Sign(rand, priv, digest) 83 if err != nil { 84 return nil, err 85 } 86 87 return asn1.Marshal(ecdsaSignature{r, s}) 88 } 89 90 var one = new(big.Int).SetInt64(1) 91 92 // randFieldElement returns a random element of the field underlying the given 93 // curve using the procedure given in [NSA] A.2.1. 94 func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) { 95 params := c.Params() 96 b := make([]byte, params.BitSize/8+8) 97 _, err = io.ReadFull(rand, b) 98 if err != nil { 99 return 100 } 101 102 k = new(big.Int).SetBytes(b) 103 n := new(big.Int).Sub(params.N, one) 104 k.Mod(k, n) 105 k.Add(k, one) 106 return 107 } 108 109 // GenerateKey generates a public and private key pair. 110 func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) { 111 k, err := randFieldElement(c, rand) 112 if err != nil { 113 return nil, err 114 } 115 116 priv := new(PrivateKey) 117 priv.PublicKey.Curve = c 118 priv.D = k 119 priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes()) 120 return priv, nil 121 } 122 123 // hashToInt converts a hash value to an integer. There is some disagreement 124 // about how this is done. [NSA] suggests that this is done in the obvious 125 // manner, but [SECG] truncates the hash to the bit-length of the curve order 126 // first. We follow [SECG] because that's what OpenSSL does. Additionally, 127 // OpenSSL right shifts excess bits from the number if the hash is too large 128 // and we mirror that too. 129 func hashToInt(hash []byte, c elliptic.Curve) *big.Int { 130 orderBits := c.Params().N.BitLen() 131 orderBytes := (orderBits + 7) / 8 132 if len(hash) > orderBytes { 133 hash = hash[:orderBytes] 134 } 135 136 ret := new(big.Int).SetBytes(hash) 137 excess := len(hash)*8 - orderBits 138 if excess > 0 { 139 ret.Rsh(ret, uint(excess)) 140 } 141 return ret 142 } 143 144 // fermatInverse calculates the inverse of k in GF(P) using Fermat's method. 145 // This has better constant-time properties than Euclid's method (implemented 146 // in math/big.Int.ModInverse) although math/big itself isn't strictly 147 // constant-time so it's not perfect. 148 func fermatInverse(k, N *big.Int) *big.Int { 149 two := big.NewInt(2) 150 nMinus2 := new(big.Int).Sub(N, two) 151 return new(big.Int).Exp(k, nMinus2, N) 152 } 153 154 var errZeroParam = errors.New("zero parameter") 155 156 // Sign signs a hash (which should be the result of hashing a larger message) 157 // using the private key, priv. If the hash is longer than the bit-length of the 158 // private key's curve order, the hash will be truncated to that length. It 159 // returns the signature as a pair of integers. The security of the private key 160 // depends on the entropy of rand. 161 func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) { 162 // randutil.MaybeReadByte(rand) 163 164 // Get min(log2(q) / 2, 256) bits of entropy from rand. 165 entropylen := (priv.Curve.Params().BitSize + 7) / 16 166 if entropylen > 32 { 167 entropylen = 32 168 } 169 entropy := make([]byte, entropylen) 170 _, err = io.ReadFull(rand, entropy) 171 if err != nil { 172 return 173 } 174 175 // Initialize an SHA-512 hash context; digest ... 176 md := sha512.New() 177 md.Write(priv.D.Bytes()) // the private key, 178 md.Write(entropy) // the entropy, 179 md.Write(hash) // and the input hash; 180 key := md.Sum(nil)[:32] // and compute ChopMD-256(SHA-512), 181 // which is an indifferentiable MAC. 182 183 // Create an AES-CTR instance to use as a CSPRNG. 184 block, err := aes.NewCipher(key) 185 if err != nil { 186 return nil, nil, err 187 } 188 189 // Create a CSPRNG that xors a stream of zeros with 190 // the output of the AES-CTR instance. 191 csprng := cipher.StreamReader{ 192 R: zeroReader, 193 S: cipher.NewCTR(block, []byte(aesIV)), 194 } 195 196 // See [NSA] 3.4.1 197 c := priv.PublicKey.Curve 198 N := c.Params().N 199 if N.Sign() == 0 { 200 return nil, nil, errZeroParam 201 } 202 203 var k *big.Int 204 var e *big.Int 205 206 if IsSM2(priv.Curve.Params()) { 207 e = GetE(&priv.PublicKey, hash) 208 for { 209 for { 210 k, err = randFieldElement(c, csprng) 211 if err != nil { 212 return nil, nil, err 213 } 214 215 r, _ = priv.Curve.ScalarBaseMult(k.Bytes()) 216 r.Add(r, e) 217 r.Mod(r, N) 218 if r.Sign() == 0 { 219 continue 220 } 221 if t := new(big.Int).Add(r, k); t.Cmp(N) == 0 { 222 continue 223 } 224 break 225 } 226 227 rD := new(big.Int).Mul(priv.D, r) 228 s = new(big.Int).Sub(k, rD) 229 d1 := new(big.Int).Add(priv.D, one) 230 var d1Inv *big.Int 231 if in, ok := priv.Curve.(invertible); ok { 232 d1Inv = in.Inverse(d1) 233 } else { 234 d1Inv = fermatInverse(d1, N) // N != 0 235 } 236 s.Mul(s, d1Inv) 237 s.Mod(s, N) 238 if s.Sign() != 0 { 239 break 240 } 241 } 242 } else { 243 e = hashToInt(hash, c) 244 var kInv *big.Int 245 for { 246 for { 247 k, err = randFieldElement(c, csprng) 248 if err != nil { 249 return nil, nil, err 250 } 251 252 if in, ok := priv.Curve.(invertible); ok { 253 kInv = in.Inverse(k) 254 } else { 255 kInv = fermatInverse(k, N) // N != 0 256 } 257 258 r, _ = priv.Curve.ScalarBaseMult(k.Bytes()) 259 r.Mod(r, N) 260 if r.Sign() != 0 { 261 break 262 } 263 } 264 265 s = new(big.Int).Mul(priv.D, r) 266 s.Add(s, e) 267 s.Mul(s, kInv) 268 s.Mod(s, N) // N != 0 269 if s.Sign() != 0 { 270 break 271 } 272 } 273 } 274 275 return r, s, nil 276 } 277 278 // Verify verifies the signature in r, s of hash using the public key, pub. Its 279 // return value records whether the signature is valid. 280 func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool { 281 // See [NSA] 3.4.2 282 c := pub.Curve 283 N := c.Params().N 284 285 if r.Sign() <= 0 || s.Sign() <= 0 { 286 return false 287 } 288 if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 { 289 return false 290 } 291 var e *big.Int 292 if IsSM2(pub.Curve.Params()) { 293 e = GetE(pub, hash) 294 t := new(big.Int).Add(r, s) 295 t.Mod(t, N) 296 if N.Sign() == 0 { 297 return false 298 } 299 // Check if implements s*g + t*p 300 var x *big.Int 301 if opt, ok := c.(combinedMult); ok { 302 x, _ = opt.CombinedMult(pub.X, pub.Y, s.Bytes(), t.Bytes()) 303 } else { 304 x1, y1 := c.ScalarBaseMult(s.Bytes()) 305 x2, y2 := c.ScalarMult(pub.X, pub.Y, t.Bytes()) 306 x, _ = c.Add(x1, y1, x2, y2) 307 } 308 309 x.Add(x, e) 310 x.Mod(x, N) 311 return x.Cmp(r) == 0 312 } 313 e = hashToInt(hash, c) 314 var w *big.Int 315 if in, ok := c.(invertible); ok { 316 w = in.Inverse(s) 317 } else { 318 w = new(big.Int).ModInverse(s, N) 319 } 320 321 u1 := e.Mul(e, w) 322 u1.Mod(u1, N) 323 u2 := w.Mul(r, w) 324 u2.Mod(u2, N) 325 326 // Check if implements S1*g + S2*p 327 var x, y *big.Int 328 if opt, ok := c.(combinedMult); ok { 329 x, y = opt.CombinedMult(pub.X, pub.Y, u1.Bytes(), u2.Bytes()) 330 } else { 331 x1, y1 := c.ScalarBaseMult(u1.Bytes()) 332 x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes()) 333 x, y = c.Add(x1, y1, x2, y2) 334 } 335 336 if x.Sign() == 0 && y.Sign() == 0 { 337 return false 338 } 339 x.Mod(x, N) 340 return x.Cmp(r) == 0 341 } 342 343 type zr struct { 344 io.Reader 345 } 346 347 // Read replaces the contents of dst with zeros. 348 func (z *zr) Read(dst []byte) (n int, err error) { 349 for i := range dst { 350 dst[i] = 0 351 } 352 return len(dst), nil 353 } 354 355 var zeroReader = &zr{}