ecdsa.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. // Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as
  5. // defined in FIPS 186-3.
  6. package ecdsa
  7. // References:
  8. // [NSA]: Suite B implementer's guide to FIPS 186-3,
  9. // http://www.nsa.gov/ia/_files/ecdsa.pdf
  10. // [SECG]: SECG, SEC1
  11. // http://www.secg.org/download/aid-780/sec1-v2.pdf
  12. import (
  13. "crypto"
  14. "crypto/elliptic"
  15. "encoding/asn1"
  16. "io"
  17. "math/big"
  18. )
  19. // PublicKey represents an ECDSA public key.
  20. type PublicKey struct {
  21. elliptic.Curve
  22. X, Y *big.Int
  23. }
  24. // PrivateKey represents a ECDSA private key.
  25. type PrivateKey struct {
  26. PublicKey
  27. D *big.Int
  28. }
  29. type ecdsaSignature struct {
  30. R, S *big.Int
  31. }
  32. // Public returns the public key corresponding to priv.
  33. func (priv *PrivateKey) Public() crypto.PublicKey {
  34. return &priv.PublicKey
  35. }
  36. // Sign signs msg with priv, reading randomness from rand. This method is
  37. // intended to support keys where the private part is kept in, for example, a
  38. // hardware module. Common uses should use the Sign function in this package
  39. // directly.
  40. func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) {
  41. r, s, err := Sign(rand, priv, msg)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return asn1.Marshal(ecdsaSignature{r, s})
  46. }
  47. var one = new(big.Int).SetInt64(1)
  48. // randFieldElement returns a random element of the field underlying the given
  49. // curve using the procedure given in [NSA] A.2.1.
  50. func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
  51. params := c.Params()
  52. b := make([]byte, params.BitSize/8+8)
  53. _, err = io.ReadFull(rand, b)
  54. if err != nil {
  55. return
  56. }
  57. k = new(big.Int).SetBytes(b)
  58. n := new(big.Int).Sub(params.N, one)
  59. k.Mod(k, n)
  60. k.Add(k, one)
  61. return
  62. }
  63. // GenerateKey generates a public and private key pair.
  64. func GenerateKey(c elliptic.Curve, rand io.Reader) (priv *PrivateKey, err error) {
  65. k, err := randFieldElement(c, rand)
  66. if err != nil {
  67. return
  68. }
  69. priv = new(PrivateKey)
  70. priv.PublicKey.Curve = c
  71. priv.D = k
  72. priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
  73. return
  74. }
  75. // hashToInt converts a hash value to an integer. There is some disagreement
  76. // about how this is done. [NSA] suggests that this is done in the obvious
  77. // manner, but [SECG] truncates the hash to the bit-length of the curve order
  78. // first. We follow [SECG] because that's what OpenSSL does. Additionally,
  79. // OpenSSL right shifts excess bits from the number if the hash is too large
  80. // and we mirror that too.
  81. func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
  82. orderBits := c.Params().N.BitLen()
  83. orderBytes := (orderBits + 7) / 8
  84. if len(hash) > orderBytes {
  85. hash = hash[:orderBytes]
  86. }
  87. ret := new(big.Int).SetBytes(hash)
  88. excess := len(hash)*8 - orderBits
  89. if excess > 0 {
  90. ret.Rsh(ret, uint(excess))
  91. }
  92. return ret
  93. }
  94. // fermatInverse calculates the inverse of k in GF(P) using Fermat's method.
  95. // This has better constant-time properties than Euclid's method (implemented
  96. // in math/big.Int.ModInverse) although math/big itself isn't strictly
  97. // constant-time so it's not perfect.
  98. func fermatInverse(k, N *big.Int) *big.Int {
  99. two := big.NewInt(2)
  100. nMinus2 := new(big.Int).Sub(N, two)
  101. return new(big.Int).Exp(k, nMinus2, N)
  102. }
  103. // Sign signs an arbitrary length hash (which should be the result of hashing a
  104. // larger message) using the private key, priv. It returns the signature as a
  105. // pair of integers. The security of the private key depends on the entropy of
  106. // rand.
  107. func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
  108. // See [NSA] 3.4.1
  109. c := priv.PublicKey.Curve
  110. N := c.Params().N
  111. var k, kInv *big.Int
  112. for {
  113. for {
  114. k, err = randFieldElement(c, rand)
  115. if err != nil {
  116. r = nil
  117. return
  118. }
  119. kInv = fermatInverse(k, N)
  120. r, _ = priv.Curve.ScalarBaseMult(k.Bytes())
  121. r.Mod(r, N)
  122. if r.Sign() != 0 {
  123. break
  124. }
  125. }
  126. e := hashToInt(hash, c)
  127. s = new(big.Int).Mul(priv.D, r)
  128. s.Add(s, e)
  129. s.Mul(s, kInv)
  130. s.Mod(s, N)
  131. if s.Sign() != 0 {
  132. break
  133. }
  134. }
  135. return
  136. }
  137. // Verify verifies the signature in r, s of hash using the public key, pub. Its
  138. // return value records whether the signature is valid.
  139. func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
  140. // See [NSA] 3.4.2
  141. c := pub.Curve
  142. N := c.Params().N
  143. if r.Sign() == 0 || s.Sign() == 0 {
  144. return false
  145. }
  146. if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
  147. return false
  148. }
  149. e := hashToInt(hash, c)
  150. w := new(big.Int).ModInverse(s, N)
  151. u1 := e.Mul(e, w)
  152. u1.Mod(u1, N)
  153. u2 := w.Mul(r, w)
  154. u2.Mod(u2, N)
  155. x1, y1 := c.ScalarBaseMult(u1.Bytes())
  156. x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes())
  157. x, y := c.Add(x1, y1, x2, y2)
  158. if x.Sign() == 0 && y.Sign() == 0 {
  159. return false
  160. }
  161. x.Mod(x, N)
  162. return x.Cmp(r) == 0
  163. }