signature.go 16 KB

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