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.
7 // For details of the algorithms used, see "Multiplication and Squaring on
8 // Pairing-Friendly Fields, Devegili et al.
9 // http://eprint.iacr.org/2006/471.pdf.
15 // gfP2 implements a field of size p² as a quadratic extension of the base
18 x, y *big.Int // value is xi+y.
21 func newGFp2(pool *bnPool) *gfP2 {
22 return &gfP2{pool.Get(), pool.Get()}
25 func (e *gfP2) String() string {
26 x := new(big.Int).Mod(e.x, p)
27 y := new(big.Int).Mod(e.y, p)
28 return "(" + x.String() + "," + y.String() + ")"
31 func (e *gfP2) Put(pool *bnPool) {
36 func (e *gfP2) Set(a *gfP2) *gfP2 {
42 func (e *gfP2) SetZero() *gfP2 {
48 func (e *gfP2) SetOne() *gfP2 {
54 func (e *gfP2) Minimal() {
55 if e.x.Sign() < 0 || e.x.Cmp(p) >= 0 {
58 if e.y.Sign() < 0 || e.y.Cmp(p) >= 0 {
63 func (e *gfP2) IsZero() bool {
64 return e.x.Sign() == 0 && e.y.Sign() == 0
67 func (e *gfP2) IsOne() bool {
72 return len(words) == 1 && words[0] == 1
75 func (e *gfP2) Conjugate(a *gfP2) *gfP2 {
81 func (e *gfP2) Negative(a *gfP2) *gfP2 {
87 func (e *gfP2) Add(a, b *gfP2) *gfP2 {
93 func (e *gfP2) Sub(a, b *gfP2) *gfP2 {
99 func (e *gfP2) Double(a *gfP2) *gfP2 {
105 func (c *gfP2) Exp(a *gfP2, power *big.Int, pool *bnPool) *gfP2 {
110 for i := power.BitLen() - 1; i >= 0; i-- {
112 if power.Bit(i) != 0 {
127 // See "Multiplication and Squaring in Pairing-Friendly Fields",
128 // http://eprint.iacr.org/2006/471.pdf
129 func (e *gfP2) Mul(a, b *gfP2, pool *bnPool) *gfP2 {
130 tx := pool.Get().Mul(a.x, b.y)
131 t := pool.Get().Mul(b.x, a.y)
135 ty := pool.Get().Mul(a.y, b.y)
148 func (e *gfP2) MulScalar(a *gfP2, b *big.Int) *gfP2 {
154 // MulXi sets e=ξa where ξ=i+3 and then returns e.
155 func (e *gfP2) MulXi(a *gfP2, pool *bnPool) *gfP2 {
156 // (xi+y)(i+3) = (3x+y)i+(3y-x)
157 tx := pool.Get().Lsh(a.x, 1)
161 ty := pool.Get().Lsh(a.y, 1)
174 func (e *gfP2) Square(a *gfP2, pool *bnPool) *gfP2 {
175 // Complex squaring algorithm:
176 // (xi+b)² = (x+y)(y-x) + 2*i*x*y
177 t1 := pool.Get().Sub(a.y, a.x)
178 t2 := pool.Get().Add(a.x, a.y)
179 ty := pool.Get().Mul(t1, t2)
195 func (e *gfP2) Invert(a *gfP2, pool *bnPool) *gfP2 {
196 // See "Implementing cryptographic pairings", M. Scott, section 3.2.
197 // ftp://136.206.11.249/pub/crypto/pairings.pdf