signature.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. // Copyright (c) 2013-2017 The btcsuite developers
  2. // Use of this source code is governed by an ISC
  3. // license that can be found in the LICENSE file.
  4. package btcec
  5. import (
  6. "bytes"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/hmac"
  10. "crypto/sha256"
  11. "errors"
  12. "fmt"
  13. "hash"
  14. "math/big"
  15. )
  16. // Errors returned by canonicalPadding.
  17. var (
  18. errNegativeValue = errors.New("value may be interpreted as negative")
  19. errExcessivelyPaddedValue = errors.New("value is excessively padded")
  20. )
  21. // Signature is a type representing an ecdsa signature.
  22. type Signature struct {
  23. R *big.Int
  24. S *big.Int
  25. }
  26. var (
  27. // Used in RFC6979 implementation when testing the nonce for correctness
  28. one = big.NewInt(1)
  29. // oneInitializer is used to fill a byte slice with byte 0x01. It is provided
  30. // here to avoid the need to create it multiple times.
  31. oneInitializer = []byte{0x01}
  32. )
  33. // Serialize returns the ECDSA signature in the more strict DER format. Note
  34. // that the serialized bytes returned do not include the appended hash type
  35. // used in Bitcoin signature scripts.
  36. //
  37. // encoding/asn1 is broken so we hand roll this output:
  38. //
  39. // 0x30 <length> 0x02 <length r> r 0x02 <length s> s
  40. func (sig *Signature) Serialize() []byte {
  41. // low 'S' malleability breaker
  42. sigS := sig.S
  43. if sigS.Cmp(S256().halfOrder) == 1 {
  44. sigS = new(big.Int).Sub(S256().N, sigS)
  45. }
  46. // Ensure the encoded bytes for the r and s values are canonical and
  47. // thus suitable for DER encoding.
  48. rb := canonicalizeInt(sig.R)
  49. sb := canonicalizeInt(sigS)
  50. // total length of returned signature is 1 byte for each magic and
  51. // length (6 total), plus lengths of r and s
  52. length := 6 + len(rb) + len(sb)
  53. b := make([]byte, length)
  54. b[0] = 0x30
  55. b[1] = byte(length - 2)
  56. b[2] = 0x02
  57. b[3] = byte(len(rb))
  58. offset := copy(b[4:], rb) + 4
  59. b[offset] = 0x02
  60. b[offset+1] = byte(len(sb))
  61. copy(b[offset+2:], sb)
  62. return b
  63. }
  64. // Verify calls ecdsa.Verify to verify the signature of hash using the public
  65. // key. It returns true if the signature is valid, false otherwise.
  66. func (sig *Signature) Verify(hash []byte, pubKey *PublicKey) bool {
  67. return ecdsa.Verify(pubKey.ToECDSA(), hash, sig.R, sig.S)
  68. }
  69. // IsEqual compares this Signature instance to the one passed, returning true
  70. // if both Signatures are equivalent. A signature is equivalent to another, if
  71. // they both have the same scalar value for R and S.
  72. func (sig *Signature) IsEqual(otherSig *Signature) bool {
  73. return sig.R.Cmp(otherSig.R) == 0 &&
  74. sig.S.Cmp(otherSig.S) == 0
  75. }
  76. func parseSig(sigStr []byte, curve elliptic.Curve, der bool) (*Signature, error) {
  77. // Originally this code used encoding/asn1 in order to parse the
  78. // signature, but a number of problems were found with this approach.
  79. // Despite the fact that signatures are stored as DER, the difference
  80. // between go's idea of a bignum (and that they have sign) doesn't agree
  81. // with the openssl one (where they do not). The above is true as of
  82. // Go 1.1. In the end it was simpler to rewrite the code to explicitly
  83. // understand the format which is this:
  84. // 0x30 <length of whole message> <0x02> <length of R> <R> 0x2
  85. // <length of S> <S>.
  86. signature := &Signature{}
  87. // minimal message is when both numbers are 1 bytes. adding up to:
  88. // 0x30 + len + 0x02 + 0x01 + <byte> + 0x2 + 0x01 + <byte>
  89. if len(sigStr) < 8 {
  90. return nil, errors.New("malformed signature: too short")
  91. }
  92. // 0x30
  93. index := 0
  94. if sigStr[index] != 0x30 {
  95. return nil, errors.New("malformed signature: no header magic")
  96. }
  97. index++
  98. // length of remaining message
  99. siglen := sigStr[index]
  100. index++
  101. if int(siglen+2) > len(sigStr) {
  102. return nil, errors.New("malformed signature: bad length")
  103. }
  104. // trim the slice we're working on so we only look at what matters.
  105. sigStr = sigStr[:siglen+2]
  106. // 0x02
  107. if sigStr[index] != 0x02 {
  108. return nil,
  109. errors.New("malformed signature: no 1st int marker")
  110. }
  111. index++
  112. // Length of signature R.
  113. rLen := int(sigStr[index])
  114. // must be positive, must be able to fit in another 0x2, <len> <s>
  115. // hence the -3. We assume that the length must be at least one byte.
  116. index++
  117. if rLen <= 0 || rLen > len(sigStr)-index-3 {
  118. return nil, errors.New("malformed signature: bogus R length")
  119. }
  120. // Then R itself.
  121. rBytes := sigStr[index : index+rLen]
  122. if der {
  123. switch err := canonicalPadding(rBytes); err {
  124. case errNegativeValue:
  125. return nil, errors.New("signature R is negative")
  126. case errExcessivelyPaddedValue:
  127. return nil, errors.New("signature R is excessively padded")
  128. }
  129. }
  130. signature.R = new(big.Int).SetBytes(rBytes)
  131. index += rLen
  132. // 0x02. length already checked in previous if.
  133. if sigStr[index] != 0x02 {
  134. return nil, errors.New("malformed signature: no 2nd int marker")
  135. }
  136. index++
  137. // Length of signature S.
  138. sLen := int(sigStr[index])
  139. index++
  140. // S should be the rest of the string.
  141. if sLen <= 0 || sLen > len(sigStr)-index {
  142. return nil, errors.New("malformed signature: bogus S length")
  143. }
  144. // Then S itself.
  145. sBytes := sigStr[index : index+sLen]
  146. if der {
  147. switch err := canonicalPadding(sBytes); err {
  148. case errNegativeValue:
  149. return nil, errors.New("signature S is negative")
  150. case errExcessivelyPaddedValue:
  151. return nil, errors.New("signature S is excessively padded")
  152. }
  153. }
  154. signature.S = new(big.Int).SetBytes(sBytes)
  155. index += sLen
  156. // sanity check length parsing
  157. if index != len(sigStr) {
  158. return nil, fmt.Errorf("malformed signature: bad final length %v != %v",
  159. index, len(sigStr))
  160. }
  161. // Verify also checks this, but we can be more sure that we parsed
  162. // correctly if we verify here too.
  163. // FWIW the ecdsa spec states that R and S must be | 1, N - 1 |
  164. // but crypto/ecdsa only checks for Sign != 0. Mirror that.
  165. if signature.R.Sign() != 1 {
  166. return nil, errors.New("signature R isn't 1 or more")
  167. }
  168. if signature.S.Sign() != 1 {
  169. return nil, errors.New("signature S isn't 1 or more")
  170. }
  171. if signature.R.Cmp(curve.Params().N) >= 0 {
  172. return nil, errors.New("signature R is >= curve.N")
  173. }
  174. if signature.S.Cmp(curve.Params().N) >= 0 {
  175. return nil, errors.New("signature S is >= curve.N")
  176. }
  177. return signature, nil
  178. }
  179. // ParseSignature parses a signature in BER format for the curve type `curve'
  180. // into a Signature type, perfoming some basic sanity checks. If parsing
  181. // according to the more strict DER format is needed, use ParseDERSignature.
  182. func ParseSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
  183. return parseSig(sigStr, curve, false)
  184. }
  185. // ParseDERSignature parses a signature in DER format for the curve type
  186. // `curve` into a Signature type. If parsing according to the less strict
  187. // BER format is needed, use ParseSignature.
  188. func ParseDERSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
  189. return parseSig(sigStr, curve, true)
  190. }
  191. // canonicalizeInt returns the bytes for the passed big integer adjusted as
  192. // necessary to ensure that a big-endian encoded integer can't possibly be
  193. // misinterpreted as a negative number. This can happen when the most
  194. // significant bit is set, so it is padded by a leading zero byte in this case.
  195. // Also, the returned bytes will have at least a single byte when the passed
  196. // value is 0. This is required for DER encoding.
  197. func canonicalizeInt(val *big.Int) []byte {
  198. b := val.Bytes()
  199. if len(b) == 0 {
  200. b = []byte{0x00}
  201. }
  202. if b[0]&0x80 != 0 {
  203. paddedBytes := make([]byte, len(b)+1)
  204. copy(paddedBytes[1:], b)
  205. b = paddedBytes
  206. }
  207. return b
  208. }
  209. // canonicalPadding checks whether a big-endian encoded integer could
  210. // possibly be misinterpreted as a negative number (even though OpenSSL
  211. // treats all numbers as unsigned), or if there is any unnecessary
  212. // leading zero padding.
  213. func canonicalPadding(b []byte) error {
  214. switch {
  215. case b[0]&0x80 == 0x80:
  216. return errNegativeValue
  217. case len(b) > 1 && b[0] == 0x00 && b[1]&0x80 != 0x80:
  218. return errExcessivelyPaddedValue
  219. default:
  220. return nil
  221. }
  222. }
  223. // hashToInt converts a hash value to an integer. There is some disagreement
  224. // about how this is done. [NSA] suggests that this is done in the obvious
  225. // manner, but [SECG] truncates the hash to the bit-length of the curve order
  226. // first. We follow [SECG] because that's what OpenSSL does. Additionally,
  227. // OpenSSL right shifts excess bits from the number if the hash is too large
  228. // and we mirror that too.
  229. // This is borrowed from crypto/ecdsa.
  230. func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
  231. orderBits := c.Params().N.BitLen()
  232. orderBytes := (orderBits + 7) / 8
  233. if len(hash) > orderBytes {
  234. hash = hash[:orderBytes]
  235. }
  236. ret := new(big.Int).SetBytes(hash)
  237. excess := len(hash)*8 - orderBits
  238. if excess > 0 {
  239. ret.Rsh(ret, uint(excess))
  240. }
  241. return ret
  242. }
  243. // recoverKeyFromSignature recoves a public key from the signature "sig" on the
  244. // given message hash "msg". Based on the algorithm found in section 5.1.5 of
  245. // SEC 1 Ver 2.0, page 47-48 (53 and 54 in the pdf). This performs the details
  246. // in the inner loop in Step 1. The counter provided is actually the j parameter
  247. // of the loop * 2 - on the first iteration of j we do the R case, else the -R
  248. // case in step 1.6. This counter is used in the bitcoin compressed signature
  249. // format and thus we match bitcoind's behaviour here.
  250. func recoverKeyFromSignature(curve *KoblitzCurve, sig *Signature, msg []byte,
  251. iter int, doChecks bool) (*PublicKey, error) {
  252. // 1.1 x = (n * i) + r
  253. Rx := new(big.Int).Mul(curve.Params().N,
  254. new(big.Int).SetInt64(int64(iter/2)))
  255. Rx.Add(Rx, sig.R)
  256. if Rx.Cmp(curve.Params().P) != -1 {
  257. return nil, errors.New("calculated Rx is larger than curve P")
  258. }
  259. // convert 02<Rx> to point R. (step 1.2 and 1.3). If we are on an odd
  260. // iteration then 1.6 will be done with -R, so we calculate the other
  261. // term when uncompressing the point.
  262. Ry, err := decompressPoint(curve, Rx, iter%2 == 1)
  263. if err != nil {
  264. return nil, err
  265. }
  266. // 1.4 Check n*R is point at infinity
  267. if doChecks {
  268. nRx, nRy := curve.ScalarMult(Rx, Ry, curve.Params().N.Bytes())
  269. if nRx.Sign() != 0 || nRy.Sign() != 0 {
  270. return nil, errors.New("n*R does not equal the point at infinity")
  271. }
  272. }
  273. // 1.5 calculate e from message using the same algorithm as ecdsa
  274. // signature calculation.
  275. e := hashToInt(msg, curve)
  276. // Step 1.6.1:
  277. // We calculate the two terms sR and eG separately multiplied by the
  278. // inverse of r (from the signature). We then add them to calculate
  279. // Q = r^-1(sR-eG)
  280. invr := new(big.Int).ModInverse(sig.R, curve.Params().N)
  281. // first term.
  282. invrS := new(big.Int).Mul(invr, sig.S)
  283. invrS.Mod(invrS, curve.Params().N)
  284. sRx, sRy := curve.ScalarMult(Rx, Ry, invrS.Bytes())
  285. // second term.
  286. e.Neg(e)
  287. e.Mod(e, curve.Params().N)
  288. e.Mul(e, invr)
  289. e.Mod(e, curve.Params().N)
  290. minuseGx, minuseGy := curve.ScalarBaseMult(e.Bytes())
  291. // TODO: this would be faster if we did a mult and add in one
  292. // step to prevent the jacobian conversion back and forth.
  293. Qx, Qy := curve.Add(sRx, sRy, minuseGx, minuseGy)
  294. return &PublicKey{
  295. Curve: curve,
  296. X: Qx,
  297. Y: Qy,
  298. }, nil
  299. }
  300. // SignCompact produces a compact signature of the data in hash with the given
  301. // private key on the given koblitz curve. The isCompressed parameter should
  302. // be used to detail if the given signature should reference a compressed
  303. // public key or not. If successful the bytes of the compact signature will be
  304. // returned in the format:
  305. // <(byte of 27+public key solution)+4 if compressed >< padded bytes for signature R><padded bytes for signature S>
  306. // where the R and S parameters are padde up to the bitlengh of the curve.
  307. func SignCompact(curve *KoblitzCurve, key *PrivateKey,
  308. hash []byte, isCompressedKey bool) ([]byte, error) {
  309. sig, err := key.Sign(hash)
  310. if err != nil {
  311. return nil, err
  312. }
  313. // bitcoind checks the bit length of R and S here. The ecdsa signature
  314. // algorithm returns R and S mod N therefore they will be the bitsize of
  315. // the curve, and thus correctly sized.
  316. for i := 0; i < (curve.H+1)*2; i++ {
  317. pk, err := recoverKeyFromSignature(curve, sig, hash, i, true)
  318. if err == nil && pk.X.Cmp(key.X) == 0 && pk.Y.Cmp(key.Y) == 0 {
  319. result := make([]byte, 1, 2*curve.byteSize+1)
  320. result[0] = 27 + byte(i)
  321. if isCompressedKey {
  322. result[0] += 4
  323. }
  324. // Not sure this needs rounding but safer to do so.
  325. curvelen := (curve.BitSize + 7) / 8
  326. // Pad R and S to curvelen if needed.
  327. bytelen := (sig.R.BitLen() + 7) / 8
  328. if bytelen < curvelen {
  329. result = append(result,
  330. make([]byte, curvelen-bytelen)...)
  331. }
  332. result = append(result, sig.R.Bytes()...)
  333. bytelen = (sig.S.BitLen() + 7) / 8
  334. if bytelen < curvelen {
  335. result = append(result,
  336. make([]byte, curvelen-bytelen)...)
  337. }
  338. result = append(result, sig.S.Bytes()...)
  339. return result, nil
  340. }
  341. }
  342. return nil, errors.New("no valid solution for pubkey found")
  343. }
  344. // RecoverCompact verifies the compact signature "signature" of "hash" for the
  345. // Koblitz curve in "curve". If the signature matches then the recovered public
  346. // key will be returned as well as a boolen if the original key was compressed
  347. // or not, else an error will be returned.
  348. func RecoverCompact(curve *KoblitzCurve, signature,
  349. hash []byte) (*PublicKey, bool, error) {
  350. bitlen := (curve.BitSize + 7) / 8
  351. if len(signature) != 1+bitlen*2 {
  352. return nil, false, errors.New("invalid compact signature size")
  353. }
  354. iteration := int((signature[0] - 27) & ^byte(4))
  355. // format is <header byte><bitlen R><bitlen S>
  356. sig := &Signature{
  357. R: new(big.Int).SetBytes(signature[1 : bitlen+1]),
  358. S: new(big.Int).SetBytes(signature[bitlen+1:]),
  359. }
  360. // The iteration used here was encoded
  361. key, err := recoverKeyFromSignature(curve, sig, hash, iteration, false)
  362. if err != nil {
  363. return nil, false, err
  364. }
  365. return key, ((signature[0] - 27) & 4) == 4, nil
  366. }
  367. // signRFC6979 generates a deterministic ECDSA signature according to RFC 6979 and BIP 62.
  368. func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) {
  369. privkey := privateKey.ToECDSA()
  370. N := S256().N
  371. halfOrder := S256().halfOrder
  372. k := nonceRFC6979(privkey.D, hash)
  373. inv := new(big.Int).ModInverse(k, N)
  374. r, _ := privkey.Curve.ScalarBaseMult(k.Bytes())
  375. if r.Cmp(N) == 1 {
  376. r.Sub(r, N)
  377. }
  378. if r.Sign() == 0 {
  379. return nil, errors.New("calculated R is zero")
  380. }
  381. e := hashToInt(hash, privkey.Curve)
  382. s := new(big.Int).Mul(privkey.D, r)
  383. s.Add(s, e)
  384. s.Mul(s, inv)
  385. s.Mod(s, N)
  386. if s.Cmp(halfOrder) == 1 {
  387. s.Sub(N, s)
  388. }
  389. if s.Sign() == 0 {
  390. return nil, errors.New("calculated S is zero")
  391. }
  392. return &Signature{R: r, S: s}, nil
  393. }
  394. // nonceRFC6979 generates an ECDSA nonce (`k`) deterministically according to RFC 6979.
  395. // It takes a 32-byte hash as an input and returns 32-byte nonce to be used in ECDSA algorithm.
  396. func nonceRFC6979(privkey *big.Int, hash []byte) *big.Int {
  397. curve := S256()
  398. q := curve.Params().N
  399. x := privkey
  400. alg := sha256.New
  401. qlen := q.BitLen()
  402. holen := alg().Size()
  403. rolen := (qlen + 7) >> 3
  404. bx := append(int2octets(x, rolen), bits2octets(hash, curve, rolen)...)
  405. // Step B
  406. v := bytes.Repeat(oneInitializer, holen)
  407. // Step C (Go zeroes the all allocated memory)
  408. k := make([]byte, holen)
  409. // Step D
  410. k = mac(alg, k, append(append(v, 0x00), bx...))
  411. // Step E
  412. v = mac(alg, k, v)
  413. // Step F
  414. k = mac(alg, k, append(append(v, 0x01), bx...))
  415. // Step G
  416. v = mac(alg, k, v)
  417. // Step H
  418. for {
  419. // Step H1
  420. var t []byte
  421. // Step H2
  422. for len(t)*8 < qlen {
  423. v = mac(alg, k, v)
  424. t = append(t, v...)
  425. }
  426. // Step H3
  427. secret := hashToInt(t, curve)
  428. if secret.Cmp(one) >= 0 && secret.Cmp(q) < 0 {
  429. return secret
  430. }
  431. k = mac(alg, k, append(v, 0x00))
  432. v = mac(alg, k, v)
  433. }
  434. }
  435. // mac returns an HMAC of the given key and message.
  436. func mac(alg func() hash.Hash, k, m []byte) []byte {
  437. h := hmac.New(alg, k)
  438. h.Write(m)
  439. return h.Sum(nil)
  440. }
  441. // https://tools.ietf.org/html/rfc6979#section-2.3.3
  442. func int2octets(v *big.Int, rolen int) []byte {
  443. out := v.Bytes()
  444. // left pad with zeros if it's too short
  445. if len(out) < rolen {
  446. out2 := make([]byte, rolen)
  447. copy(out2[rolen-len(out):], out)
  448. return out2
  449. }
  450. // drop most significant bytes if it's too long
  451. if len(out) > rolen {
  452. out2 := make([]byte, rolen)
  453. copy(out2, out[len(out)-rolen:])
  454. return out2
  455. }
  456. return out
  457. }
  458. // https://tools.ietf.org/html/rfc6979#section-2.3.4
  459. func bits2octets(in []byte, curve elliptic.Curve, rolen int) []byte {
  460. z1 := hashToInt(in, curve)
  461. z2 := new(big.Int).Sub(z1, curve.Params().N)
  462. if z2.Sign() < 0 {
  463. return int2octets(z1, rolen)
  464. }
  465. return int2octets(z2, rolen)
  466. }