curve.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 crypto
  32. import (
  33. "crypto/elliptic"
  34. "io"
  35. "math/big"
  36. "sync"
  37. )
  38. // This code is from https://github.com/ThePiachu/GoBit and implements
  39. // several Koblitz elliptic curves over prime fields.
  40. //
  41. // The curve methods, internally, on Jacobian coordinates. For a given
  42. // (x, y) position on the curve, the Jacobian coordinates are (x1, y1,
  43. // z1) where x = x1/z1² and y = y1/z1³. The greatest speedups come
  44. // when the whole calculation can be performed within the transform
  45. // (as in ScalarMult and ScalarBaseMult). But even for Add and Double,
  46. // it's faster to apply and reverse the transform than to operate in
  47. // affine coordinates.
  48. // A BitCurve represents a Koblitz Curve with a=0.
  49. // See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html
  50. type BitCurve struct {
  51. P *big.Int // the order of the underlying field
  52. N *big.Int // the order of the base point
  53. B *big.Int // the constant of the BitCurve equation
  54. Gx, Gy *big.Int // (x,y) of the base point
  55. BitSize int // the size of the underlying field
  56. }
  57. func (BitCurve *BitCurve) Params() *elliptic.CurveParams {
  58. return &elliptic.CurveParams{
  59. P: BitCurve.P,
  60. N: BitCurve.N,
  61. B: BitCurve.B,
  62. Gx: BitCurve.Gx,
  63. Gy: BitCurve.Gy,
  64. BitSize: BitCurve.BitSize,
  65. }
  66. }
  67. // IsOnBitCurve returns true if the given (x,y) lies on the BitCurve.
  68. func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool {
  69. // y² = x³ + b
  70. y2 := new(big.Int).Mul(y, y) //y²
  71. y2.Mod(y2, BitCurve.P) //y²%P
  72. x3 := new(big.Int).Mul(x, x) //x²
  73. x3.Mul(x3, x) //x³
  74. x3.Add(x3, BitCurve.B) //x³+B
  75. x3.Mod(x3, BitCurve.P) //(x³+B)%P
  76. return x3.Cmp(y2) == 0
  77. }
  78. //TODO: double check if the function is okay
  79. // affineFromJacobian reverses the Jacobian transform. See the comment at the
  80. // top of the file.
  81. func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) {
  82. zinv := new(big.Int).ModInverse(z, BitCurve.P)
  83. zinvsq := new(big.Int).Mul(zinv, zinv)
  84. xOut = new(big.Int).Mul(x, zinvsq)
  85. xOut.Mod(xOut, BitCurve.P)
  86. zinvsq.Mul(zinvsq, zinv)
  87. yOut = new(big.Int).Mul(y, zinvsq)
  88. yOut.Mod(yOut, BitCurve.P)
  89. return
  90. }
  91. // Add returns the sum of (x1,y1) and (x2,y2)
  92. func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
  93. z := new(big.Int).SetInt64(1)
  94. return BitCurve.affineFromJacobian(BitCurve.addJacobian(x1, y1, z, x2, y2, z))
  95. }
  96. // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and
  97. // (x2, y2, z2) and returns their sum, also in Jacobian form.
  98. func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {
  99. // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
  100. z1z1 := new(big.Int).Mul(z1, z1)
  101. z1z1.Mod(z1z1, BitCurve.P)
  102. z2z2 := new(big.Int).Mul(z2, z2)
  103. z2z2.Mod(z2z2, BitCurve.P)
  104. u1 := new(big.Int).Mul(x1, z2z2)
  105. u1.Mod(u1, BitCurve.P)
  106. u2 := new(big.Int).Mul(x2, z1z1)
  107. u2.Mod(u2, BitCurve.P)
  108. h := new(big.Int).Sub(u2, u1)
  109. if h.Sign() == -1 {
  110. h.Add(h, BitCurve.P)
  111. }
  112. i := new(big.Int).Lsh(h, 1)
  113. i.Mul(i, i)
  114. j := new(big.Int).Mul(h, i)
  115. s1 := new(big.Int).Mul(y1, z2)
  116. s1.Mul(s1, z2z2)
  117. s1.Mod(s1, BitCurve.P)
  118. s2 := new(big.Int).Mul(y2, z1)
  119. s2.Mul(s2, z1z1)
  120. s2.Mod(s2, BitCurve.P)
  121. r := new(big.Int).Sub(s2, s1)
  122. if r.Sign() == -1 {
  123. r.Add(r, BitCurve.P)
  124. }
  125. r.Lsh(r, 1)
  126. v := new(big.Int).Mul(u1, i)
  127. x3 := new(big.Int).Set(r)
  128. x3.Mul(x3, x3)
  129. x3.Sub(x3, j)
  130. x3.Sub(x3, v)
  131. x3.Sub(x3, v)
  132. x3.Mod(x3, BitCurve.P)
  133. y3 := new(big.Int).Set(r)
  134. v.Sub(v, x3)
  135. y3.Mul(y3, v)
  136. s1.Mul(s1, j)
  137. s1.Lsh(s1, 1)
  138. y3.Sub(y3, s1)
  139. y3.Mod(y3, BitCurve.P)
  140. z3 := new(big.Int).Add(z1, z2)
  141. z3.Mul(z3, z3)
  142. z3.Sub(z3, z1z1)
  143. if z3.Sign() == -1 {
  144. z3.Add(z3, BitCurve.P)
  145. }
  146. z3.Sub(z3, z2z2)
  147. if z3.Sign() == -1 {
  148. z3.Add(z3, BitCurve.P)
  149. }
  150. z3.Mul(z3, h)
  151. z3.Mod(z3, BitCurve.P)
  152. return x3, y3, z3
  153. }
  154. // Double returns 2*(x,y)
  155. func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {
  156. z1 := new(big.Int).SetInt64(1)
  157. return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z1))
  158. }
  159. // doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
  160. // returns its double, also in Jacobian form.
  161. func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
  162. // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
  163. a := new(big.Int).Mul(x, x) //X1²
  164. b := new(big.Int).Mul(y, y) //Y1²
  165. c := new(big.Int).Mul(b, b) //B²
  166. d := new(big.Int).Add(x, b) //X1+B
  167. d.Mul(d, d) //(X1+B)²
  168. d.Sub(d, a) //(X1+B)²-A
  169. d.Sub(d, c) //(X1+B)²-A-C
  170. d.Mul(d, big.NewInt(2)) //2*((X1+B)²-A-C)
  171. e := new(big.Int).Mul(big.NewInt(3), a) //3*A
  172. f := new(big.Int).Mul(e, e) //E²
  173. x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D
  174. x3.Sub(f, x3) //F-2*D
  175. x3.Mod(x3, BitCurve.P)
  176. y3 := new(big.Int).Sub(d, x3) //D-X3
  177. y3.Mul(e, y3) //E*(D-X3)
  178. y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C
  179. y3.Mod(y3, BitCurve.P)
  180. z3 := new(big.Int).Mul(y, z) //Y1*Z1
  181. z3.Mul(big.NewInt(2), z3) //3*Y1*Z1
  182. z3.Mod(z3, BitCurve.P)
  183. return x3, y3, z3
  184. }
  185. //TODO: double check if it is okay
  186. // ScalarMult returns k*(Bx,By) where k is a number in big-endian form.
  187. func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) {
  188. // We have a slight problem in that the identity of the group (the
  189. // point at infinity) cannot be represented in (x, y) form on a finite
  190. // machine. Thus the standard add/double algorithm has to be tweaked
  191. // slightly: our initial state is not the identity, but x, and we
  192. // ignore the first true bit in |k|. If we don't find any true bits in
  193. // |k|, then we return nil, nil, because we cannot return the identity
  194. // element.
  195. Bz := new(big.Int).SetInt64(1)
  196. x := Bx
  197. y := By
  198. z := Bz
  199. seenFirstTrue := false
  200. for _, byte := range k {
  201. for bitNum := 0; bitNum < 8; bitNum++ {
  202. if seenFirstTrue {
  203. x, y, z = BitCurve.doubleJacobian(x, y, z)
  204. }
  205. if byte&0x80 == 0x80 {
  206. if !seenFirstTrue {
  207. seenFirstTrue = true
  208. } else {
  209. x, y, z = BitCurve.addJacobian(Bx, By, Bz, x, y, z)
  210. }
  211. }
  212. byte <<= 1
  213. }
  214. }
  215. if !seenFirstTrue {
  216. return nil, nil
  217. }
  218. return BitCurve.affineFromJacobian(x, y, z)
  219. }
  220. // ScalarBaseMult returns k*G, where G is the base point of the group and k is
  221. // an integer in big-endian form.
  222. func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) {
  223. return BitCurve.ScalarMult(BitCurve.Gx, BitCurve.Gy, k)
  224. }
  225. var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
  226. //TODO: double check if it is okay
  227. // GenerateKey returns a public/private key pair. The private key is generated
  228. // using the given reader, which must return random data.
  229. func (BitCurve *BitCurve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) {
  230. byteLen := (BitCurve.BitSize + 7) >> 3
  231. priv = make([]byte, byteLen)
  232. for x == nil {
  233. _, err = io.ReadFull(rand, priv)
  234. if err != nil {
  235. return
  236. }
  237. // We have to mask off any excess bits in the case that the size of the
  238. // underlying field is not a whole number of bytes.
  239. priv[0] &= mask[BitCurve.BitSize%8]
  240. // This is because, in tests, rand will return all zeros and we don't
  241. // want to get the point at infinity and loop forever.
  242. priv[1] ^= 0x42
  243. x, y = BitCurve.ScalarBaseMult(priv)
  244. }
  245. return
  246. }
  247. // Marshal converts a point into the form specified in section 4.3.6 of ANSI
  248. // X9.62.
  249. func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte {
  250. byteLen := (BitCurve.BitSize + 7) >> 3
  251. ret := make([]byte, 1+2*byteLen)
  252. ret[0] = 4 // uncompressed point
  253. xBytes := x.Bytes()
  254. copy(ret[1+byteLen-len(xBytes):], xBytes)
  255. yBytes := y.Bytes()
  256. copy(ret[1+2*byteLen-len(yBytes):], yBytes)
  257. return ret
  258. }
  259. // Unmarshal converts a point, serialised by Marshal, into an x, y pair. On
  260. // error, x = nil.
  261. func (BitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) {
  262. byteLen := (BitCurve.BitSize + 7) >> 3
  263. if len(data) != 1+2*byteLen {
  264. return
  265. }
  266. if data[0] != 4 { // uncompressed form
  267. return
  268. }
  269. x = new(big.Int).SetBytes(data[1 : 1+byteLen])
  270. y = new(big.Int).SetBytes(data[1+byteLen:])
  271. return
  272. }
  273. //curve parameters taken from:
  274. //http://www.secg.org/collateral/sec2_final.pdf
  275. var initonce sync.Once
  276. var ecp160k1 *BitCurve
  277. var ecp192k1 *BitCurve
  278. var ecp224k1 *BitCurve
  279. var ecp256k1 *BitCurve
  280. func initAll() {
  281. initS160()
  282. initS192()
  283. initS224()
  284. initS256()
  285. }
  286. func initS160() {
  287. // See SEC 2 section 2.4.1
  288. ecp160k1 = new(BitCurve)
  289. ecp160k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", 16)
  290. ecp160k1.N, _ = new(big.Int).SetString("0100000000000000000001B8FA16DFAB9ACA16B6B3", 16)
  291. ecp160k1.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000007", 16)
  292. ecp160k1.Gx, _ = new(big.Int).SetString("3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", 16)
  293. ecp160k1.Gy, _ = new(big.Int).SetString("938CF935318FDCED6BC28286531733C3F03C4FEE", 16)
  294. ecp160k1.BitSize = 160
  295. }
  296. func initS192() {
  297. // See SEC 2 section 2.5.1
  298. ecp192k1 = new(BitCurve)
  299. ecp192k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", 16)
  300. ecp192k1.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", 16)
  301. ecp192k1.B, _ = new(big.Int).SetString("000000000000000000000000000000000000000000000003", 16)
  302. ecp192k1.Gx, _ = new(big.Int).SetString("DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", 16)
  303. ecp192k1.Gy, _ = new(big.Int).SetString("9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", 16)
  304. ecp192k1.BitSize = 192
  305. }
  306. func initS224() {
  307. // See SEC 2 section 2.6.1
  308. ecp224k1 = new(BitCurve)
  309. ecp224k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", 16)
  310. ecp224k1.N, _ = new(big.Int).SetString("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7", 16)
  311. ecp224k1.B, _ = new(big.Int).SetString("00000000000000000000000000000000000000000000000000000005", 16)
  312. ecp224k1.Gx, _ = new(big.Int).SetString("A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", 16)
  313. ecp224k1.Gy, _ = new(big.Int).SetString("7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", 16)
  314. ecp224k1.BitSize = 224
  315. }
  316. func initS256() {
  317. // See SEC 2 section 2.7.1
  318. ecp256k1 = new(BitCurve)
  319. ecp256k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16)
  320. ecp256k1.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
  321. ecp256k1.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000007", 16)
  322. ecp256k1.Gx, _ = new(big.Int).SetString("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16)
  323. ecp256k1.Gy, _ = new(big.Int).SetString("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16)
  324. ecp256k1.BitSize = 256
  325. }
  326. // S160 returns a BitCurve which implements secp160k1 (see SEC 2 section 2.4.1)
  327. func S160() *BitCurve {
  328. initonce.Do(initAll)
  329. return ecp160k1
  330. }
  331. // S192 returns a BitCurve which implements secp192k1 (see SEC 2 section 2.5.1)
  332. func S192() *BitCurve {
  333. initonce.Do(initAll)
  334. return ecp192k1
  335. }
  336. // S224 returns a BitCurve which implements secp224k1 (see SEC 2 section 2.6.1)
  337. func S224() *BitCurve {
  338. initonce.Do(initAll)
  339. return ecp224k1
  340. }
  341. // S256 returns a BitCurve which implements secp256k1 (see SEC 2 section 2.7.1)
  342. func S256() *BitCurve {
  343. initonce.Do(initAll)
  344. return ecp256k1
  345. }