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