nonce.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // Copyright (c) 2013-2014 The btcsuite developers
  2. // Copyright (c) 2015-2020 The Decred developers
  3. // Use of this source code is governed by an ISC
  4. // license that can be found in the LICENSE file.
  5. package secp256k1
  6. import (
  7. "bytes"
  8. "crypto/sha256"
  9. "hash"
  10. )
  11. // References:
  12. // [GECC]: Guide to Elliptic Curve Cryptography (Hankerson, Menezes, Vanstone)
  13. //
  14. // [ISO/IEC 8825-1]: Information technology — ASN.1 encoding rules:
  15. // Specification of Basic Encoding Rules (BER), Canonical Encoding Rules
  16. // (CER) and Distinguished Encoding Rules (DER)
  17. //
  18. // [SEC1]: Elliptic Curve Cryptography (May 31, 2009, Version 2.0)
  19. // https://www.secg.org/sec1-v2.pdf
  20. var (
  21. // singleZero is used during RFC6979 nonce generation. It is provided
  22. // here to avoid the need to create it multiple times.
  23. singleZero = []byte{0x00}
  24. // zeroInitializer is used during RFC6979 nonce generation. It is provided
  25. // here to avoid the need to create it multiple times.
  26. zeroInitializer = bytes.Repeat([]byte{0x00}, sha256.BlockSize)
  27. // singleOne is used during RFC6979 nonce generation. It is provided
  28. // here to avoid the need to create it multiple times.
  29. singleOne = []byte{0x01}
  30. // oneInitializer is used during RFC6979 nonce generation. It is provided
  31. // here to avoid the need to create it multiple times.
  32. oneInitializer = bytes.Repeat([]byte{0x01}, sha256.Size)
  33. )
  34. // hmacsha256 implements a resettable version of HMAC-SHA256.
  35. type hmacsha256 struct {
  36. inner, outer hash.Hash
  37. ipad, opad [sha256.BlockSize]byte
  38. }
  39. // Write adds data to the running hash.
  40. func (h *hmacsha256) Write(p []byte) {
  41. h.inner.Write(p)
  42. }
  43. // initKey initializes the HMAC-SHA256 instance to the provided key.
  44. func (h *hmacsha256) initKey(key []byte) {
  45. // Hash the key if it is too large.
  46. if len(key) > sha256.BlockSize {
  47. h.outer.Write(key)
  48. key = h.outer.Sum(nil)
  49. }
  50. copy(h.ipad[:], key)
  51. copy(h.opad[:], key)
  52. for i := range h.ipad {
  53. h.ipad[i] ^= 0x36
  54. }
  55. for i := range h.opad {
  56. h.opad[i] ^= 0x5c
  57. }
  58. h.inner.Write(h.ipad[:])
  59. }
  60. // ResetKey resets the HMAC-SHA256 to its initial state and then initializes it
  61. // with the provided key. It is equivalent to creating a new instance with the
  62. // provided key without allocating more memory.
  63. func (h *hmacsha256) ResetKey(key []byte) {
  64. h.inner.Reset()
  65. h.outer.Reset()
  66. copy(h.ipad[:], zeroInitializer)
  67. copy(h.opad[:], zeroInitializer)
  68. h.initKey(key)
  69. }
  70. // Resets the HMAC-SHA256 to its initial state using the current key.
  71. func (h *hmacsha256) Reset() {
  72. h.inner.Reset()
  73. h.inner.Write(h.ipad[:])
  74. }
  75. // Sum returns the hash of the written data.
  76. func (h *hmacsha256) Sum() []byte {
  77. h.outer.Reset()
  78. h.outer.Write(h.opad[:])
  79. h.outer.Write(h.inner.Sum(nil))
  80. return h.outer.Sum(nil)
  81. }
  82. // newHMACSHA256 returns a new HMAC-SHA256 hasher using the provided key.
  83. func newHMACSHA256(key []byte) *hmacsha256 {
  84. h := new(hmacsha256)
  85. h.inner = sha256.New()
  86. h.outer = sha256.New()
  87. h.initKey(key)
  88. return h
  89. }
  90. // NonceRFC6979 generates a nonce deterministically according to RFC 6979 using
  91. // HMAC-SHA256 for the hashing function. It takes a 32-byte hash as an input
  92. // and returns a 32-byte nonce to be used for deterministic signing. The extra
  93. // and version arguments are optional, but allow additional data to be added to
  94. // the input of the HMAC. When provided, the extra data must be 32-bytes and
  95. // version must be 16 bytes or they will be ignored.
  96. //
  97. // Finally, the extraIterations parameter provides a method to produce a stream
  98. // of deterministic nonces to ensure the signing code is able to produce a nonce
  99. // that results in a valid signature in the extremely unlikely event the
  100. // original nonce produced results in an invalid signature (e.g. R == 0).
  101. // Signing code should start with 0 and increment it if necessary.
  102. func NonceRFC6979(privKey []byte, hash []byte, extra []byte, version []byte, extraIterations uint32) *ModNScalar {
  103. // Input to HMAC is the 32-byte private key and the 32-byte hash. In
  104. // addition, it may include the optional 32-byte extra data and 16-byte
  105. // version. Create a fixed-size array to avoid extra allocs and slice it
  106. // properly.
  107. const (
  108. privKeyLen = 32
  109. hashLen = 32
  110. extraLen = 32
  111. versionLen = 16
  112. )
  113. var keyBuf [privKeyLen + hashLen + extraLen + versionLen]byte
  114. // Truncate rightmost bytes of private key and hash if they are too long and
  115. // leave left padding of zeros when they're too short.
  116. if len(privKey) > privKeyLen {
  117. privKey = privKey[:privKeyLen]
  118. }
  119. if len(hash) > hashLen {
  120. hash = hash[:hashLen]
  121. }
  122. offset := privKeyLen - len(privKey) // Zero left padding if needed.
  123. offset += copy(keyBuf[offset:], privKey)
  124. offset += hashLen - len(hash) // Zero left padding if needed.
  125. offset += copy(keyBuf[offset:], hash)
  126. if len(extra) == extraLen {
  127. offset += copy(keyBuf[offset:], extra)
  128. if len(version) == versionLen {
  129. offset += copy(keyBuf[offset:], version)
  130. }
  131. } else if len(version) == versionLen {
  132. // When the version was specified, but not the extra data, leave the
  133. // extra data portion all zero.
  134. offset += privKeyLen
  135. offset += copy(keyBuf[offset:], version)
  136. }
  137. key := keyBuf[:offset]
  138. // Step B.
  139. //
  140. // V = 0x01 0x01 0x01 ... 0x01 such that the length of V, in bits, is
  141. // equal to 8*ceil(hashLen/8).
  142. //
  143. // Note that since the hash length is a multiple of 8 for the chosen hash
  144. // function in this optimized implementation, the result is just the hash
  145. // length, so avoid the extra calculations. Also, since it isn't modified,
  146. // start with a global value.
  147. v := oneInitializer
  148. // Step C (Go zeroes all allocated memory).
  149. //
  150. // K = 0x00 0x00 0x00 ... 0x00 such that the length of K, in bits, is
  151. // equal to 8*ceil(hashLen/8).
  152. //
  153. // As above, since the hash length is a multiple of 8 for the chosen hash
  154. // function in this optimized implementation, the result is just the hash
  155. // length, so avoid the extra calculations.
  156. k := zeroInitializer[:hashLen]
  157. // Step D.
  158. //
  159. // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1))
  160. //
  161. // Note that key is the "int2octets(x) || bits2octets(h1)" portion along
  162. // with potential additional data as described by section 3.6 of the RFC.
  163. hasher := newHMACSHA256(k)
  164. hasher.Write(oneInitializer)
  165. hasher.Write(singleZero[:])
  166. hasher.Write(key)
  167. k = hasher.Sum()
  168. // Step E.
  169. //
  170. // V = HMAC_K(V)
  171. hasher.ResetKey(k)
  172. hasher.Write(v)
  173. v = hasher.Sum()
  174. // Step F.
  175. //
  176. // K = HMAC_K(V || 0x01 || int2octets(x) || bits2octets(h1))
  177. //
  178. // Note that key is the "int2octets(x) || bits2octets(h1)" portion along
  179. // with potential additional data as described by section 3.6 of the RFC.
  180. hasher.Reset()
  181. hasher.Write(v)
  182. hasher.Write(singleOne[:])
  183. hasher.Write(key[:])
  184. k = hasher.Sum()
  185. // Step G.
  186. //
  187. // V = HMAC_K(V)
  188. hasher.ResetKey(k)
  189. hasher.Write(v)
  190. v = hasher.Sum()
  191. // Step H.
  192. //
  193. // Repeat until the value is nonzero and less than the curve order.
  194. var generated uint32
  195. for {
  196. // Step H1 and H2.
  197. //
  198. // Set T to the empty sequence. The length of T (in bits) is denoted
  199. // tlen; thus, at that point, tlen = 0.
  200. //
  201. // While tlen < qlen, do the following:
  202. // V = HMAC_K(V)
  203. // T = T || V
  204. //
  205. // Note that because the hash function output is the same length as the
  206. // private key in this optimized implementation, there is no need to
  207. // loop or create an intermediate T.
  208. hasher.Reset()
  209. hasher.Write(v)
  210. v = hasher.Sum()
  211. // Step H3.
  212. //
  213. // k = bits2int(T)
  214. // If k is within the range [1,q-1], return it.
  215. //
  216. // Otherwise, compute:
  217. // K = HMAC_K(V || 0x00)
  218. // V = HMAC_K(V)
  219. var secret ModNScalar
  220. overflow := secret.SetByteSlice(v)
  221. if !overflow && !secret.IsZero() {
  222. generated++
  223. if generated > extraIterations {
  224. return &secret
  225. }
  226. }
  227. // K = HMAC_K(V || 0x00)
  228. hasher.Reset()
  229. hasher.Write(v)
  230. hasher.Write(singleZero[:])
  231. k = hasher.Sum()
  232. // V = HMAC_K(V)
  233. hasher.ResetKey(k)
  234. hasher.Write(v)
  235. v = hasher.Sum()
  236. }
  237. }