curve.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Copyright 2011 ThePiachu. All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. // * The name of ThePiachu may not be used to endorse or promote products
  18. // derived from this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. package secp256k1
  32. import (
  33. "crypto/elliptic"
  34. "io"
  35. "math/big"
  36. "sync"
  37. "unsafe"
  38. )
  39. /*
  40. #include "libsecp256k1/include/secp256k1.h"
  41. extern int secp256k1_pubkey_scalar_mul(const secp256k1_context* ctx, const unsigned char *point, const unsigned char *scalar);
  42. */
  43. import "C"
  44. // This code is from https://github.com/ThePiachu/GoBit and implements
  45. // several Koblitz elliptic curves over prime fields.
  46. //
  47. // The curve methods, internally, on Jacobian coordinates. For a given
  48. // (x, y) position on the curve, the Jacobian coordinates are (x1, y1,
  49. // z1) where x = x1/z1² and y = y1/z1³. The greatest speedups come
  50. // when the whole calculation can be performed within the transform
  51. // (as in ScalarMult and ScalarBaseMult). But even for Add and Double,
  52. // it's faster to apply and reverse the transform than to operate in
  53. // affine coordinates.
  54. // A BitCurve represents a Koblitz Curve with a=0.
  55. // See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html
  56. type BitCurve struct {
  57. P *big.Int // the order of the underlying field
  58. N *big.Int // the order of the base point
  59. B *big.Int // the constant of the BitCurve equation
  60. Gx, Gy *big.Int // (x,y) of the base point
  61. BitSize int // the size of the underlying field
  62. }
  63. func (BitCurve *BitCurve) Params() *elliptic.CurveParams {
  64. return &elliptic.CurveParams{
  65. P: BitCurve.P,
  66. N: BitCurve.N,
  67. B: BitCurve.B,
  68. Gx: BitCurve.Gx,
  69. Gy: BitCurve.Gy,
  70. BitSize: BitCurve.BitSize,
  71. }
  72. }
  73. // IsOnBitCurve returns true if the given (x,y) lies on the BitCurve.
  74. func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool {
  75. // y² = x³ + b
  76. y2 := new(big.Int).Mul(y, y) //y²
  77. y2.Mod(y2, BitCurve.P) //y²%P
  78. x3 := new(big.Int).Mul(x, x) //x²
  79. x3.Mul(x3, x) //x³
  80. x3.Add(x3, BitCurve.B) //x³+B
  81. x3.Mod(x3, BitCurve.P) //(x³+B)%P
  82. return x3.Cmp(y2) == 0
  83. }
  84. //TODO: double check if the function is okay
  85. // affineFromJacobian reverses the Jacobian transform. See the comment at the
  86. // top of the file.
  87. func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) {
  88. zinv := new(big.Int).ModInverse(z, BitCurve.P)
  89. zinvsq := new(big.Int).Mul(zinv, zinv)
  90. xOut = new(big.Int).Mul(x, zinvsq)
  91. xOut.Mod(xOut, BitCurve.P)
  92. zinvsq.Mul(zinvsq, zinv)
  93. yOut = new(big.Int).Mul(y, zinvsq)
  94. yOut.Mod(yOut, BitCurve.P)
  95. return
  96. }
  97. // Add returns the sum of (x1,y1) and (x2,y2)
  98. func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
  99. z := new(big.Int).SetInt64(1)
  100. return BitCurve.affineFromJacobian(BitCurve.addJacobian(x1, y1, z, x2, y2, z))
  101. }
  102. // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and
  103. // (x2, y2, z2) and returns their sum, also in Jacobian form.
  104. func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {
  105. // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
  106. z1z1 := new(big.Int).Mul(z1, z1)
  107. z1z1.Mod(z1z1, BitCurve.P)
  108. z2z2 := new(big.Int).Mul(z2, z2)
  109. z2z2.Mod(z2z2, BitCurve.P)
  110. u1 := new(big.Int).Mul(x1, z2z2)
  111. u1.Mod(u1, BitCurve.P)
  112. u2 := new(big.Int).Mul(x2, z1z1)
  113. u2.Mod(u2, BitCurve.P)
  114. h := new(big.Int).Sub(u2, u1)
  115. if h.Sign() == -1 {
  116. h.Add(h, BitCurve.P)
  117. }
  118. i := new(big.Int).Lsh(h, 1)
  119. i.Mul(i, i)
  120. j := new(big.Int).Mul(h, i)
  121. s1 := new(big.Int).Mul(y1, z2)
  122. s1.Mul(s1, z2z2)
  123. s1.Mod(s1, BitCurve.P)
  124. s2 := new(big.Int).Mul(y2, z1)
  125. s2.Mul(s2, z1z1)
  126. s2.Mod(s2, BitCurve.P)
  127. r := new(big.Int).Sub(s2, s1)
  128. if r.Sign() == -1 {
  129. r.Add(r, BitCurve.P)
  130. }
  131. r.Lsh(r, 1)
  132. v := new(big.Int).Mul(u1, i)
  133. x3 := new(big.Int).Set(r)
  134. x3.Mul(x3, x3)
  135. x3.Sub(x3, j)
  136. x3.Sub(x3, v)
  137. x3.Sub(x3, v)
  138. x3.Mod(x3, BitCurve.P)
  139. y3 := new(big.Int).Set(r)
  140. v.Sub(v, x3)
  141. y3.Mul(y3, v)
  142. s1.Mul(s1, j)
  143. s1.Lsh(s1, 1)
  144. y3.Sub(y3, s1)
  145. y3.Mod(y3, BitCurve.P)
  146. z3 := new(big.Int).Add(z1, z2)
  147. z3.Mul(z3, z3)
  148. z3.Sub(z3, z1z1)
  149. if z3.Sign() == -1 {
  150. z3.Add(z3, BitCurve.P)
  151. }
  152. z3.Sub(z3, z2z2)
  153. if z3.Sign() == -1 {
  154. z3.Add(z3, BitCurve.P)
  155. }
  156. z3.Mul(z3, h)
  157. z3.Mod(z3, BitCurve.P)
  158. return x3, y3, z3
  159. }
  160. // Double returns 2*(x,y)
  161. func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {
  162. z1 := new(big.Int).SetInt64(1)
  163. return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z1))
  164. }
  165. // doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
  166. // returns its double, also in Jacobian form.
  167. func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
  168. // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
  169. a := new(big.Int).Mul(x, x) //X1²
  170. b := new(big.Int).Mul(y, y) //Y1²
  171. c := new(big.Int).Mul(b, b) //B²
  172. d := new(big.Int).Add(x, b) //X1+B
  173. d.Mul(d, d) //(X1+B)²
  174. d.Sub(d, a) //(X1+B)²-A
  175. d.Sub(d, c) //(X1+B)²-A-C
  176. d.Mul(d, big.NewInt(2)) //2*((X1+B)²-A-C)
  177. e := new(big.Int).Mul(big.NewInt(3), a) //3*A
  178. f := new(big.Int).Mul(e, e) //E²
  179. x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D
  180. x3.Sub(f, x3) //F-2*D
  181. x3.Mod(x3, BitCurve.P)
  182. y3 := new(big.Int).Sub(d, x3) //D-X3
  183. y3.Mul(e, y3) //E*(D-X3)
  184. y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C
  185. y3.Mod(y3, BitCurve.P)
  186. z3 := new(big.Int).Mul(y, z) //Y1*Z1
  187. z3.Mul(big.NewInt(2), z3) //3*Y1*Z1
  188. z3.Mod(z3, BitCurve.P)
  189. return x3, y3, z3
  190. }
  191. func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, *big.Int) {
  192. // Ensure scalar is exactly 32 bytes. We pad always, even if
  193. // scalar is 32 bytes long, to avoid a timing side channel.
  194. if len(scalar) > 32 {
  195. panic("can't handle scalars > 256 bits")
  196. }
  197. padded := make([]byte, 32)
  198. copy(padded[32-len(scalar):], scalar)
  199. scalar = padded
  200. // Do the multiplication in C, updating point.
  201. point := make([]byte, 64)
  202. readBits(point[:32], Bx)
  203. readBits(point[32:], By)
  204. pointPtr := (*C.uchar)(unsafe.Pointer(&point[0]))
  205. scalarPtr := (*C.uchar)(unsafe.Pointer(&scalar[0]))
  206. res := C.secp256k1_pubkey_scalar_mul(context, pointPtr, scalarPtr)
  207. // Unpack the result and clear temporaries.
  208. x := new(big.Int).SetBytes(point[:32])
  209. y := new(big.Int).SetBytes(point[32:])
  210. for i := range point {
  211. point[i] = 0
  212. }
  213. for i := range padded {
  214. scalar[i] = 0
  215. }
  216. if res != 1 {
  217. return nil, nil
  218. }
  219. return x, y
  220. }
  221. // ScalarBaseMult returns k*G, where G is the base point of the group and k is
  222. // an integer in big-endian form.
  223. func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) {
  224. return BitCurve.ScalarMult(BitCurve.Gx, BitCurve.Gy, k)
  225. }
  226. var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
  227. //TODO: double check if it is okay
  228. // GenerateKey returns a public/private key pair. The private key is generated
  229. // using the given reader, which must return random data.
  230. func (BitCurve *BitCurve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) {
  231. byteLen := (BitCurve.BitSize + 7) >> 3
  232. priv = make([]byte, byteLen)
  233. for x == nil {
  234. _, err = io.ReadFull(rand, priv)
  235. if err != nil {
  236. return
  237. }
  238. // We have to mask off any excess bits in the case that the size of the
  239. // underlying field is not a whole number of bytes.
  240. priv[0] &= mask[BitCurve.BitSize%8]
  241. // This is because, in tests, rand will return all zeros and we don't
  242. // want to get the point at infinity and loop forever.
  243. priv[1] ^= 0x42
  244. x, y = BitCurve.ScalarBaseMult(priv)
  245. }
  246. return
  247. }
  248. // Marshal converts a point into the form specified in section 4.3.6 of ANSI
  249. // X9.62.
  250. func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte {
  251. byteLen := (BitCurve.BitSize + 7) >> 3
  252. ret := make([]byte, 1+2*byteLen)
  253. ret[0] = 4 // uncompressed point
  254. xBytes := x.Bytes()
  255. copy(ret[1+byteLen-len(xBytes):], xBytes)
  256. yBytes := y.Bytes()
  257. copy(ret[1+2*byteLen-len(yBytes):], yBytes)
  258. return ret
  259. }
  260. // Unmarshal converts a point, serialised by Marshal, into an x, y pair. On
  261. // error, x = nil.
  262. func (BitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) {
  263. byteLen := (BitCurve.BitSize + 7) >> 3
  264. if len(data) != 1+2*byteLen {
  265. return
  266. }
  267. if data[0] != 4 { // uncompressed form
  268. return
  269. }
  270. x = new(big.Int).SetBytes(data[1 : 1+byteLen])
  271. y = new(big.Int).SetBytes(data[1+byteLen:])
  272. return
  273. }
  274. var (
  275. initonce sync.Once
  276. theCurve *BitCurve
  277. )
  278. // S256 returns a BitCurve which implements secp256k1 (see SEC 2 section 2.7.1)
  279. func S256() *BitCurve {
  280. initonce.Do(func() {
  281. // See SEC 2 section 2.7.1
  282. // curve parameters taken from:
  283. // http://www.secg.org/collateral/sec2_final.pdf
  284. theCurve = new(BitCurve)
  285. theCurve.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16)
  286. theCurve.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
  287. theCurve.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000007", 16)
  288. theCurve.Gx, _ = new(big.Int).SetString("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16)
  289. theCurve.Gy, _ = new(big.Int).SetString("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16)
  290. theCurve.BitSize = 256
  291. })
  292. return theCurve
  293. }