bn256.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package bn256 implements a particular bilinear group.
  5. //
  6. // Bilinear groups are the basis of many of the new cryptographic protocols
  7. // that have been proposed over the past decade. They consist of a triplet of
  8. // groups (G₁, G₂ and GT) such that there exists a function e(g₁ˣ,g₂ʸ)=gTˣʸ
  9. // (where gₓ is a generator of the respective group). That function is called
  10. // a pairing function.
  11. //
  12. // This package specifically implements the Optimal Ate pairing over a 256-bit
  13. // Barreto-Naehrig curve as described in
  14. // http://cryptojedi.org/papers/dclxvi-20100714.pdf. Its output is not
  15. // compatible with the implementation described in that paper, as different
  16. // parameters are chosen.
  17. //
  18. // (This package previously claimed to operate at a 128-bit security level.
  19. // However, recent improvements in attacks mean that is no longer true. See
  20. // https://moderncrypto.org/mail-archive/curves/2016/000740.html.)
  21. package bn256
  22. import (
  23. "crypto/rand"
  24. "errors"
  25. "io"
  26. "math/big"
  27. )
  28. // BUG(agl): this implementation is not constant time.
  29. // TODO(agl): keep GF(p²) elements in Mongomery form.
  30. // G1 is an abstract cyclic group. The zero value is suitable for use as the
  31. // output of an operation, but cannot be used as an input.
  32. type G1 struct {
  33. p *curvePoint
  34. }
  35. // RandomG1 returns x and g₁ˣ where x is a random, non-zero number read from r.
  36. func RandomG1(r io.Reader) (*big.Int, *G1, error) {
  37. var k *big.Int
  38. var err error
  39. for {
  40. k, err = rand.Int(r, Order)
  41. if err != nil {
  42. return nil, nil, err
  43. }
  44. if k.Sign() > 0 {
  45. break
  46. }
  47. }
  48. return k, new(G1).ScalarBaseMult(k), nil
  49. }
  50. func (e *G1) String() string {
  51. return "bn256.G1" + e.p.String()
  52. }
  53. // CurvePoints returns p's curve points in big integer
  54. func (e *G1) CurvePoints() (*big.Int, *big.Int, *big.Int, *big.Int) {
  55. return e.p.x, e.p.y, e.p.z, e.p.t
  56. }
  57. // ScalarBaseMult sets e to g*k where g is the generator of the group and
  58. // then returns e.
  59. func (e *G1) ScalarBaseMult(k *big.Int) *G1 {
  60. if e.p == nil {
  61. e.p = newCurvePoint(nil)
  62. }
  63. e.p.Mul(curveGen, k, new(bnPool))
  64. return e
  65. }
  66. // ScalarMult sets e to a*k and then returns e.
  67. func (e *G1) ScalarMult(a *G1, k *big.Int) *G1 {
  68. if e.p == nil {
  69. e.p = newCurvePoint(nil)
  70. }
  71. e.p.Mul(a.p, k, new(bnPool))
  72. return e
  73. }
  74. // Add sets e to a+b and then returns e.
  75. // BUG(agl): this function is not complete: a==b fails.
  76. func (e *G1) Add(a, b *G1) *G1 {
  77. if e.p == nil {
  78. e.p = newCurvePoint(nil)
  79. }
  80. e.p.Add(a.p, b.p, new(bnPool))
  81. return e
  82. }
  83. // Neg sets e to -a and then returns e.
  84. func (e *G1) Neg(a *G1) *G1 {
  85. if e.p == nil {
  86. e.p = newCurvePoint(nil)
  87. }
  88. e.p.Negative(a.p)
  89. return e
  90. }
  91. // Marshal converts n to a byte slice.
  92. func (e *G1) Marshal() []byte {
  93. // Each value is a 256-bit number.
  94. const numBytes = 256 / 8
  95. if e.p.IsInfinity() {
  96. return make([]byte, numBytes*2)
  97. }
  98. e.p.MakeAffine(nil)
  99. xBytes := new(big.Int).Mod(e.p.x, P).Bytes()
  100. yBytes := new(big.Int).Mod(e.p.y, P).Bytes()
  101. ret := make([]byte, numBytes*2)
  102. copy(ret[1*numBytes-len(xBytes):], xBytes)
  103. copy(ret[2*numBytes-len(yBytes):], yBytes)
  104. return ret
  105. }
  106. // Unmarshal sets e to the result of converting the output of Marshal back into
  107. // a group element and then returns e.
  108. func (e *G1) Unmarshal(m []byte) ([]byte, error) {
  109. // Each value is a 256-bit number.
  110. const numBytes = 256 / 8
  111. if len(m) != 2*numBytes {
  112. return nil, errors.New("bn256: not enough data")
  113. }
  114. // Unmarshal the points and check their caps
  115. if e.p == nil {
  116. e.p = newCurvePoint(nil)
  117. }
  118. e.p.x.SetBytes(m[0*numBytes : 1*numBytes])
  119. if e.p.x.Cmp(P) >= 0 {
  120. return nil, errors.New("bn256: coordinate exceeds modulus")
  121. }
  122. e.p.y.SetBytes(m[1*numBytes : 2*numBytes])
  123. if e.p.y.Cmp(P) >= 0 {
  124. return nil, errors.New("bn256: coordinate exceeds modulus")
  125. }
  126. // Ensure the point is on the curve
  127. if e.p.x.Sign() == 0 && e.p.y.Sign() == 0 {
  128. // This is the point at infinity.
  129. e.p.y.SetInt64(1)
  130. e.p.z.SetInt64(0)
  131. e.p.t.SetInt64(0)
  132. } else {
  133. e.p.z.SetInt64(1)
  134. e.p.t.SetInt64(1)
  135. if !e.p.IsOnCurve() {
  136. return nil, errors.New("bn256: malformed point")
  137. }
  138. }
  139. return m[2*numBytes:], nil
  140. }
  141. // G2 is an abstract cyclic group. The zero value is suitable for use as the
  142. // output of an operation, but cannot be used as an input.
  143. type G2 struct {
  144. p *twistPoint
  145. }
  146. // RandomG1 returns x and g₂ˣ where x is a random, non-zero number read from r.
  147. func RandomG2(r io.Reader) (*big.Int, *G2, error) {
  148. var k *big.Int
  149. var err error
  150. for {
  151. k, err = rand.Int(r, Order)
  152. if err != nil {
  153. return nil, nil, err
  154. }
  155. if k.Sign() > 0 {
  156. break
  157. }
  158. }
  159. return k, new(G2).ScalarBaseMult(k), nil
  160. }
  161. func (e *G2) String() string {
  162. return "bn256.G2" + e.p.String()
  163. }
  164. // CurvePoints returns the curve points of p which includes the real
  165. // and imaginary parts of the curve point.
  166. func (e *G2) CurvePoints() (*gfP2, *gfP2, *gfP2, *gfP2) {
  167. return e.p.x, e.p.y, e.p.z, e.p.t
  168. }
  169. // ScalarBaseMult sets e to g*k where g is the generator of the group and
  170. // then returns out.
  171. func (e *G2) ScalarBaseMult(k *big.Int) *G2 {
  172. if e.p == nil {
  173. e.p = newTwistPoint(nil)
  174. }
  175. e.p.Mul(twistGen, k, new(bnPool))
  176. return e
  177. }
  178. // ScalarMult sets e to a*k and then returns e.
  179. func (e *G2) ScalarMult(a *G2, k *big.Int) *G2 {
  180. if e.p == nil {
  181. e.p = newTwistPoint(nil)
  182. }
  183. e.p.Mul(a.p, k, new(bnPool))
  184. return e
  185. }
  186. // Add sets e to a+b and then returns e.
  187. // BUG(agl): this function is not complete: a==b fails.
  188. func (e *G2) Add(a, b *G2) *G2 {
  189. if e.p == nil {
  190. e.p = newTwistPoint(nil)
  191. }
  192. e.p.Add(a.p, b.p, new(bnPool))
  193. return e
  194. }
  195. // Marshal converts n into a byte slice.
  196. func (n *G2) Marshal() []byte {
  197. // Each value is a 256-bit number.
  198. const numBytes = 256 / 8
  199. if n.p.IsInfinity() {
  200. return make([]byte, numBytes*4)
  201. }
  202. n.p.MakeAffine(nil)
  203. xxBytes := new(big.Int).Mod(n.p.x.x, P).Bytes()
  204. xyBytes := new(big.Int).Mod(n.p.x.y, P).Bytes()
  205. yxBytes := new(big.Int).Mod(n.p.y.x, P).Bytes()
  206. yyBytes := new(big.Int).Mod(n.p.y.y, P).Bytes()
  207. ret := make([]byte, numBytes*4)
  208. copy(ret[1*numBytes-len(xxBytes):], xxBytes)
  209. copy(ret[2*numBytes-len(xyBytes):], xyBytes)
  210. copy(ret[3*numBytes-len(yxBytes):], yxBytes)
  211. copy(ret[4*numBytes-len(yyBytes):], yyBytes)
  212. return ret
  213. }
  214. // Unmarshal sets e to the result of converting the output of Marshal back into
  215. // a group element and then returns e.
  216. func (e *G2) Unmarshal(m []byte) ([]byte, error) {
  217. // Each value is a 256-bit number.
  218. const numBytes = 256 / 8
  219. if len(m) != 4*numBytes {
  220. return nil, errors.New("bn256: not enough data")
  221. }
  222. // Unmarshal the points and check their caps
  223. if e.p == nil {
  224. e.p = newTwistPoint(nil)
  225. }
  226. e.p.x.x.SetBytes(m[0*numBytes : 1*numBytes])
  227. if e.p.x.x.Cmp(P) >= 0 {
  228. return nil, errors.New("bn256: coordinate exceeds modulus")
  229. }
  230. e.p.x.y.SetBytes(m[1*numBytes : 2*numBytes])
  231. if e.p.x.y.Cmp(P) >= 0 {
  232. return nil, errors.New("bn256: coordinate exceeds modulus")
  233. }
  234. e.p.y.x.SetBytes(m[2*numBytes : 3*numBytes])
  235. if e.p.y.x.Cmp(P) >= 0 {
  236. return nil, errors.New("bn256: coordinate exceeds modulus")
  237. }
  238. e.p.y.y.SetBytes(m[3*numBytes : 4*numBytes])
  239. if e.p.y.y.Cmp(P) >= 0 {
  240. return nil, errors.New("bn256: coordinate exceeds modulus")
  241. }
  242. // Ensure the point is on the curve
  243. if e.p.x.x.Sign() == 0 &&
  244. e.p.x.y.Sign() == 0 &&
  245. e.p.y.x.Sign() == 0 &&
  246. e.p.y.y.Sign() == 0 {
  247. // This is the point at infinity.
  248. e.p.y.SetOne()
  249. e.p.z.SetZero()
  250. e.p.t.SetZero()
  251. } else {
  252. e.p.z.SetOne()
  253. e.p.t.SetOne()
  254. if !e.p.IsOnCurve() {
  255. return nil, errors.New("bn256: malformed point")
  256. }
  257. }
  258. return m[4*numBytes:], nil
  259. }
  260. // GT is an abstract cyclic group. The zero value is suitable for use as the
  261. // output of an operation, but cannot be used as an input.
  262. type GT struct {
  263. p *gfP12
  264. }
  265. func (g *GT) String() string {
  266. return "bn256.GT" + g.p.String()
  267. }
  268. // ScalarMult sets e to a*k and then returns e.
  269. func (e *GT) ScalarMult(a *GT, k *big.Int) *GT {
  270. if e.p == nil {
  271. e.p = newGFp12(nil)
  272. }
  273. e.p.Exp(a.p, k, new(bnPool))
  274. return e
  275. }
  276. // Add sets e to a+b and then returns e.
  277. func (e *GT) Add(a, b *GT) *GT {
  278. if e.p == nil {
  279. e.p = newGFp12(nil)
  280. }
  281. e.p.Mul(a.p, b.p, new(bnPool))
  282. return e
  283. }
  284. // Neg sets e to -a and then returns e.
  285. func (e *GT) Neg(a *GT) *GT {
  286. if e.p == nil {
  287. e.p = newGFp12(nil)
  288. }
  289. e.p.Invert(a.p, new(bnPool))
  290. return e
  291. }
  292. // Marshal converts n into a byte slice.
  293. func (n *GT) Marshal() []byte {
  294. n.p.Minimal()
  295. xxxBytes := n.p.x.x.x.Bytes()
  296. xxyBytes := n.p.x.x.y.Bytes()
  297. xyxBytes := n.p.x.y.x.Bytes()
  298. xyyBytes := n.p.x.y.y.Bytes()
  299. xzxBytes := n.p.x.z.x.Bytes()
  300. xzyBytes := n.p.x.z.y.Bytes()
  301. yxxBytes := n.p.y.x.x.Bytes()
  302. yxyBytes := n.p.y.x.y.Bytes()
  303. yyxBytes := n.p.y.y.x.Bytes()
  304. yyyBytes := n.p.y.y.y.Bytes()
  305. yzxBytes := n.p.y.z.x.Bytes()
  306. yzyBytes := n.p.y.z.y.Bytes()
  307. // Each value is a 256-bit number.
  308. const numBytes = 256 / 8
  309. ret := make([]byte, numBytes*12)
  310. copy(ret[1*numBytes-len(xxxBytes):], xxxBytes)
  311. copy(ret[2*numBytes-len(xxyBytes):], xxyBytes)
  312. copy(ret[3*numBytes-len(xyxBytes):], xyxBytes)
  313. copy(ret[4*numBytes-len(xyyBytes):], xyyBytes)
  314. copy(ret[5*numBytes-len(xzxBytes):], xzxBytes)
  315. copy(ret[6*numBytes-len(xzyBytes):], xzyBytes)
  316. copy(ret[7*numBytes-len(yxxBytes):], yxxBytes)
  317. copy(ret[8*numBytes-len(yxyBytes):], yxyBytes)
  318. copy(ret[9*numBytes-len(yyxBytes):], yyxBytes)
  319. copy(ret[10*numBytes-len(yyyBytes):], yyyBytes)
  320. copy(ret[11*numBytes-len(yzxBytes):], yzxBytes)
  321. copy(ret[12*numBytes-len(yzyBytes):], yzyBytes)
  322. return ret
  323. }
  324. // Unmarshal sets e to the result of converting the output of Marshal back into
  325. // a group element and then returns e.
  326. func (e *GT) Unmarshal(m []byte) (*GT, bool) {
  327. // Each value is a 256-bit number.
  328. const numBytes = 256 / 8
  329. if len(m) != 12*numBytes {
  330. return nil, false
  331. }
  332. if e.p == nil {
  333. e.p = newGFp12(nil)
  334. }
  335. e.p.x.x.x.SetBytes(m[0*numBytes : 1*numBytes])
  336. e.p.x.x.y.SetBytes(m[1*numBytes : 2*numBytes])
  337. e.p.x.y.x.SetBytes(m[2*numBytes : 3*numBytes])
  338. e.p.x.y.y.SetBytes(m[3*numBytes : 4*numBytes])
  339. e.p.x.z.x.SetBytes(m[4*numBytes : 5*numBytes])
  340. e.p.x.z.y.SetBytes(m[5*numBytes : 6*numBytes])
  341. e.p.y.x.x.SetBytes(m[6*numBytes : 7*numBytes])
  342. e.p.y.x.y.SetBytes(m[7*numBytes : 8*numBytes])
  343. e.p.y.y.x.SetBytes(m[8*numBytes : 9*numBytes])
  344. e.p.y.y.y.SetBytes(m[9*numBytes : 10*numBytes])
  345. e.p.y.z.x.SetBytes(m[10*numBytes : 11*numBytes])
  346. e.p.y.z.y.SetBytes(m[11*numBytes : 12*numBytes])
  347. return e, true
  348. }
  349. // Pair calculates an Optimal Ate pairing.
  350. func Pair(g1 *G1, g2 *G2) *GT {
  351. return &GT{optimalAte(g2.p, g1.p, new(bnPool))}
  352. }
  353. // PairingCheck calculates the Optimal Ate pairing for a set of points.
  354. func PairingCheck(a []*G1, b []*G2) bool {
  355. pool := new(bnPool)
  356. acc := newGFp12(pool)
  357. acc.SetOne()
  358. for i := 0; i < len(a); i++ {
  359. if a[i].p.IsInfinity() || b[i].p.IsInfinity() {
  360. continue
  361. }
  362. acc.Mul(acc, miller(b[i].p, a[i].p, pool), pool)
  363. }
  364. ret := finalExponentiation(acc, pool)
  365. acc.Put(pool)
  366. return ret.IsOne()
  367. }
  368. // bnPool implements a tiny cache of *big.Int objects that's used to reduce the
  369. // number of allocations made during processing.
  370. type bnPool struct {
  371. bns []*big.Int
  372. count int
  373. }
  374. func (pool *bnPool) Get() *big.Int {
  375. if pool == nil {
  376. return new(big.Int)
  377. }
  378. pool.count++
  379. l := len(pool.bns)
  380. if l == 0 {
  381. return new(big.Int)
  382. }
  383. bn := pool.bns[l-1]
  384. pool.bns = pool.bns[:l-1]
  385. return bn
  386. }
  387. func (pool *bnPool) Put(bn *big.Int) {
  388. if pool == nil {
  389. return
  390. }
  391. pool.bns = append(pool.bns, bn)
  392. pool.count--
  393. }
  394. func (pool *bnPool) Count() int {
  395. return pool.count
  396. }