Source file src/crypto/internal/fips140/edwards25519/field/fe.go

     1  // Copyright (c) 2017 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  
     5  // Package field implements fast arithmetic modulo 2^255-19.
     6  package field
     7  
     8  import (
     9  	_ "crypto/internal/fips140/check"
    10  	"crypto/internal/fips140/subtle"
    11  	"crypto/internal/fips140deps/byteorder"
    12  	"errors"
    13  	"math/bits"
    14  )
    15  
    16  // Element represents an element of the field GF(2^255-19). Note that this
    17  // is not a cryptographically secure group, and should only be used to interact
    18  // with edwards25519.Point coordinates.
    19  //
    20  // This type works similarly to math/big.Int, and all arguments and receivers
    21  // are allowed to alias.
    22  //
    23  // The zero value is a valid zero element.
    24  type Element struct {
    25  	// An element t represents the integer
    26  	//     t.l0 + t.l1*2^51 + t.l2*2^102 + t.l3*2^153 + t.l4*2^204
    27  	//
    28  	// Between operations, all limbs are expected to be lower than 2^52.
    29  	l0 uint64
    30  	l1 uint64
    31  	l2 uint64
    32  	l3 uint64
    33  	l4 uint64
    34  }
    35  
    36  const maskLow51Bits uint64 = (1 << 51) - 1
    37  
    38  var feZero = &Element{0, 0, 0, 0, 0}
    39  
    40  // Zero sets v = 0, and returns v.
    41  func (v *Element) Zero() *Element {
    42  	*v = *feZero
    43  	return v
    44  }
    45  
    46  var feOne = &Element{1, 0, 0, 0, 0}
    47  
    48  // One sets v = 1, and returns v.
    49  func (v *Element) One() *Element {
    50  	*v = *feOne
    51  	return v
    52  }
    53  
    54  // reduce reduces v modulo 2^255 - 19 and returns it.
    55  func (v *Element) reduce() *Element {
    56  	v.carryPropagate()
    57  
    58  	// After the light reduction we now have a field element representation
    59  	// v < 2^255 + 2^13 * 19, but need v < 2^255 - 19.
    60  
    61  	// If v >= 2^255 - 19, then v + 19 >= 2^255, which would overflow 2^255 - 1,
    62  	// generating a carry. That is, c will be 0 if v < 2^255 - 19, and 1 otherwise.
    63  	c := (v.l0 + 19) >> 51
    64  	c = (v.l1 + c) >> 51
    65  	c = (v.l2 + c) >> 51
    66  	c = (v.l3 + c) >> 51
    67  	c = (v.l4 + c) >> 51
    68  
    69  	// If v < 2^255 - 19 and c = 0, this will be a no-op. Otherwise, it's
    70  	// effectively applying the reduction identity to the carry.
    71  	v.l0 += 19 * c
    72  
    73  	v.l1 += v.l0 >> 51
    74  	v.l0 = v.l0 & maskLow51Bits
    75  	v.l2 += v.l1 >> 51
    76  	v.l1 = v.l1 & maskLow51Bits
    77  	v.l3 += v.l2 >> 51
    78  	v.l2 = v.l2 & maskLow51Bits
    79  	v.l4 += v.l3 >> 51
    80  	v.l3 = v.l3 & maskLow51Bits
    81  	// no additional carry
    82  	v.l4 = v.l4 & maskLow51Bits
    83  
    84  	return v
    85  }
    86  
    87  // Add sets v = a + b, and returns v.
    88  func (v *Element) Add(a, b *Element) *Element {
    89  	v.l0 = a.l0 + b.l0
    90  	v.l1 = a.l1 + b.l1
    91  	v.l2 = a.l2 + b.l2
    92  	v.l3 = a.l3 + b.l3
    93  	v.l4 = a.l4 + b.l4
    94  	// Using the generic implementation here is actually faster than the
    95  	// assembly. Probably because the body of this function is so simple that
    96  	// the compiler can figure out better optimizations by inlining the carry
    97  	// propagation.
    98  	return v.carryPropagateGeneric()
    99  }
   100  
   101  // Subtract sets v = a - b, and returns v.
   102  func (v *Element) Subtract(a, b *Element) *Element {
   103  	// We first add 2 * p, to guarantee the subtraction won't underflow, and
   104  	// then subtract b (which can be up to 2^255 + 2^13 * 19).
   105  	v.l0 = (a.l0 + 0xFFFFFFFFFFFDA) - b.l0
   106  	v.l1 = (a.l1 + 0xFFFFFFFFFFFFE) - b.l1
   107  	v.l2 = (a.l2 + 0xFFFFFFFFFFFFE) - b.l2
   108  	v.l3 = (a.l3 + 0xFFFFFFFFFFFFE) - b.l3
   109  	v.l4 = (a.l4 + 0xFFFFFFFFFFFFE) - b.l4
   110  	return v.carryPropagate()
   111  }
   112  
   113  // Negate sets v = -a, and returns v.
   114  func (v *Element) Negate(a *Element) *Element {
   115  	return v.Subtract(feZero, a)
   116  }
   117  
   118  // Invert sets v = 1/z mod p, and returns v.
   119  //
   120  // If z == 0, Invert returns v = 0.
   121  func (v *Element) Invert(z *Element) *Element {
   122  	// Inversion is implemented as exponentiation with exponent p − 2. It uses the
   123  	// same sequence of 255 squarings and 11 multiplications as [Curve25519].
   124  	var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t Element
   125  
   126  	z2.Square(z)             // 2
   127  	t.Square(&z2)            // 4
   128  	t.Square(&t)             // 8
   129  	z9.Multiply(&t, z)       // 9
   130  	z11.Multiply(&z9, &z2)   // 11
   131  	t.Square(&z11)           // 22
   132  	z2_5_0.Multiply(&t, &z9) // 31 = 2^5 - 2^0
   133  
   134  	t.Square(&z2_5_0) // 2^6 - 2^1
   135  	for i := 0; i < 4; i++ {
   136  		t.Square(&t) // 2^10 - 2^5
   137  	}
   138  	z2_10_0.Multiply(&t, &z2_5_0) // 2^10 - 2^0
   139  
   140  	t.Square(&z2_10_0) // 2^11 - 2^1
   141  	for i := 0; i < 9; i++ {
   142  		t.Square(&t) // 2^20 - 2^10
   143  	}
   144  	z2_20_0.Multiply(&t, &z2_10_0) // 2^20 - 2^0
   145  
   146  	t.Square(&z2_20_0) // 2^21 - 2^1
   147  	for i := 0; i < 19; i++ {
   148  		t.Square(&t) // 2^40 - 2^20
   149  	}
   150  	t.Multiply(&t, &z2_20_0) // 2^40 - 2^0
   151  
   152  	t.Square(&t) // 2^41 - 2^1
   153  	for i := 0; i < 9; i++ {
   154  		t.Square(&t) // 2^50 - 2^10
   155  	}
   156  	z2_50_0.Multiply(&t, &z2_10_0) // 2^50 - 2^0
   157  
   158  	t.Square(&z2_50_0) // 2^51 - 2^1
   159  	for i := 0; i < 49; i++ {
   160  		t.Square(&t) // 2^100 - 2^50
   161  	}
   162  	z2_100_0.Multiply(&t, &z2_50_0) // 2^100 - 2^0
   163  
   164  	t.Square(&z2_100_0) // 2^101 - 2^1
   165  	for i := 0; i < 99; i++ {
   166  		t.Square(&t) // 2^200 - 2^100
   167  	}
   168  	t.Multiply(&t, &z2_100_0) // 2^200 - 2^0
   169  
   170  	t.Square(&t) // 2^201 - 2^1
   171  	for i := 0; i < 49; i++ {
   172  		t.Square(&t) // 2^250 - 2^50
   173  	}
   174  	t.Multiply(&t, &z2_50_0) // 2^250 - 2^0
   175  
   176  	t.Square(&t) // 2^251 - 2^1
   177  	t.Square(&t) // 2^252 - 2^2
   178  	t.Square(&t) // 2^253 - 2^3
   179  	t.Square(&t) // 2^254 - 2^4
   180  	t.Square(&t) // 2^255 - 2^5
   181  
   182  	return v.Multiply(&t, &z11) // 2^255 - 21
   183  }
   184  
   185  // Set sets v = a, and returns v.
   186  func (v *Element) Set(a *Element) *Element {
   187  	*v = *a
   188  	return v
   189  }
   190  
   191  // SetBytes sets v to x, where x is a 32-byte little-endian encoding. If x is
   192  // not of the right length, SetBytes returns nil and an error, and the
   193  // receiver is unchanged.
   194  //
   195  // Consistent with RFC 7748, the most significant bit (the high bit of the
   196  // last byte) is ignored, and non-canonical values (2^255-19 through 2^255-1)
   197  // are accepted. Note that this is laxer than specified by RFC 8032, but
   198  // consistent with most Ed25519 implementations.
   199  func (v *Element) SetBytes(x []byte) (*Element, error) {
   200  	if len(x) != 32 {
   201  		return nil, errors.New("edwards25519: invalid field element input size")
   202  	}
   203  
   204  	// Bits 0:51 (bytes 0:8, bits 0:64, shift 0, mask 51).
   205  	v.l0 = byteorder.LEUint64(x[0:8])
   206  	v.l0 &= maskLow51Bits
   207  	// Bits 51:102 (bytes 6:14, bits 48:112, shift 3, mask 51).
   208  	v.l1 = byteorder.LEUint64(x[6:14]) >> 3
   209  	v.l1 &= maskLow51Bits
   210  	// Bits 102:153 (bytes 12:20, bits 96:160, shift 6, mask 51).
   211  	v.l2 = byteorder.LEUint64(x[12:20]) >> 6
   212  	v.l2 &= maskLow51Bits
   213  	// Bits 153:204 (bytes 19:27, bits 152:216, shift 1, mask 51).
   214  	v.l3 = byteorder.LEUint64(x[19:27]) >> 1
   215  	v.l3 &= maskLow51Bits
   216  	// Bits 204:255 (bytes 24:32, bits 192:256, shift 12, mask 51).
   217  	// Note: not bytes 25:33, shift 4, to avoid overread.
   218  	v.l4 = byteorder.LEUint64(x[24:32]) >> 12
   219  	v.l4 &= maskLow51Bits
   220  
   221  	return v, nil
   222  }
   223  
   224  // Bytes returns the canonical 32-byte little-endian encoding of v.
   225  func (v *Element) Bytes() []byte {
   226  	// This function is outlined to make the allocations inline in the caller
   227  	// rather than happen on the heap.
   228  	var out [32]byte
   229  	return v.bytes(&out)
   230  }
   231  
   232  func (v *Element) bytes(out *[32]byte) []byte {
   233  	t := *v
   234  	t.reduce()
   235  
   236  	var buf [8]byte
   237  	for i, l := range [5]uint64{t.l0, t.l1, t.l2, t.l3, t.l4} {
   238  		bitsOffset := i * 51
   239  		byteorder.LEPutUint64(buf[:], l<<uint(bitsOffset%8))
   240  		for i, bb := range buf {
   241  			off := bitsOffset/8 + i
   242  			if off >= len(out) {
   243  				break
   244  			}
   245  			out[off] |= bb
   246  		}
   247  	}
   248  
   249  	return out[:]
   250  }
   251  
   252  // Equal returns 1 if v and u are equal, and 0 otherwise.
   253  func (v *Element) Equal(u *Element) int {
   254  	sa, sv := u.Bytes(), v.Bytes()
   255  	return subtle.ConstantTimeCompare(sa, sv)
   256  }
   257  
   258  // mask64Bits returns 0xffffffff if cond is 1, and 0 otherwise.
   259  func mask64Bits(cond int) uint64 { return ^(uint64(cond) - 1) }
   260  
   261  // Select sets v to a if cond == 1, and to b if cond == 0.
   262  func (v *Element) Select(a, b *Element, cond int) *Element {
   263  	m := mask64Bits(cond)
   264  	v.l0 = (m & a.l0) | (^m & b.l0)
   265  	v.l1 = (m & a.l1) | (^m & b.l1)
   266  	v.l2 = (m & a.l2) | (^m & b.l2)
   267  	v.l3 = (m & a.l3) | (^m & b.l3)
   268  	v.l4 = (m & a.l4) | (^m & b.l4)
   269  	return v
   270  }
   271  
   272  // Swap swaps v and u if cond == 1 or leaves them unchanged if cond == 0, and returns v.
   273  func (v *Element) Swap(u *Element, cond int) {
   274  	m := mask64Bits(cond)
   275  	t := m & (v.l0 ^ u.l0)
   276  	v.l0 ^= t
   277  	u.l0 ^= t
   278  	t = m & (v.l1 ^ u.l1)
   279  	v.l1 ^= t
   280  	u.l1 ^= t
   281  	t = m & (v.l2 ^ u.l2)
   282  	v.l2 ^= t
   283  	u.l2 ^= t
   284  	t = m & (v.l3 ^ u.l3)
   285  	v.l3 ^= t
   286  	u.l3 ^= t
   287  	t = m & (v.l4 ^ u.l4)
   288  	v.l4 ^= t
   289  	u.l4 ^= t
   290  }
   291  
   292  // IsNegative returns 1 if v is negative, and 0 otherwise.
   293  func (v *Element) IsNegative() int {
   294  	return int(v.Bytes()[0] & 1)
   295  }
   296  
   297  // Absolute sets v to |u|, and returns v.
   298  func (v *Element) Absolute(u *Element) *Element {
   299  	return v.Select(new(Element).Negate(u), u, u.IsNegative())
   300  }
   301  
   302  // Multiply sets v = x * y, and returns v.
   303  func (v *Element) Multiply(x, y *Element) *Element {
   304  	feMul(v, x, y)
   305  	return v
   306  }
   307  
   308  // Square sets v = x * x, and returns v.
   309  func (v *Element) Square(x *Element) *Element {
   310  	feSquare(v, x)
   311  	return v
   312  }
   313  
   314  // Mult32 sets v = x * y, and returns v.
   315  func (v *Element) Mult32(x *Element, y uint32) *Element {
   316  	x0lo, x0hi := mul51(x.l0, y)
   317  	x1lo, x1hi := mul51(x.l1, y)
   318  	x2lo, x2hi := mul51(x.l2, y)
   319  	x3lo, x3hi := mul51(x.l3, y)
   320  	x4lo, x4hi := mul51(x.l4, y)
   321  	v.l0 = x0lo + 19*x4hi // carried over per the reduction identity
   322  	v.l1 = x1lo + x0hi
   323  	v.l2 = x2lo + x1hi
   324  	v.l3 = x3lo + x2hi
   325  	v.l4 = x4lo + x3hi
   326  	// The hi portions are going to be only 32 bits, plus any previous excess,
   327  	// so we can skip the carry propagation.
   328  	return v
   329  }
   330  
   331  // mul51 returns lo + hi * 2⁵¹ = a * b.
   332  func mul51(a uint64, b uint32) (lo uint64, hi uint64) {
   333  	mh, ml := bits.Mul64(a, uint64(b))
   334  	lo = ml & maskLow51Bits
   335  	hi = (mh << 13) | (ml >> 51)
   336  	return
   337  }
   338  
   339  // Pow22523 set v = x^((p-5)/8), and returns v. (p-5)/8 is 2^252-3.
   340  func (v *Element) Pow22523(x *Element) *Element {
   341  	var t0, t1, t2 Element
   342  
   343  	t0.Square(x)             // x^2
   344  	t1.Square(&t0)           // x^4
   345  	t1.Square(&t1)           // x^8
   346  	t1.Multiply(x, &t1)      // x^9
   347  	t0.Multiply(&t0, &t1)    // x^11
   348  	t0.Square(&t0)           // x^22
   349  	t0.Multiply(&t1, &t0)    // x^31
   350  	t1.Square(&t0)           // x^62
   351  	for i := 1; i < 5; i++ { // x^992
   352  		t1.Square(&t1)
   353  	}
   354  	t0.Multiply(&t1, &t0)     // x^1023 -> 1023 = 2^10 - 1
   355  	t1.Square(&t0)            // 2^11 - 2
   356  	for i := 1; i < 10; i++ { // 2^20 - 2^10
   357  		t1.Square(&t1)
   358  	}
   359  	t1.Multiply(&t1, &t0)     // 2^20 - 1
   360  	t2.Square(&t1)            // 2^21 - 2
   361  	for i := 1; i < 20; i++ { // 2^40 - 2^20
   362  		t2.Square(&t2)
   363  	}
   364  	t1.Multiply(&t2, &t1)     // 2^40 - 1
   365  	t1.Square(&t1)            // 2^41 - 2
   366  	for i := 1; i < 10; i++ { // 2^50 - 2^10
   367  		t1.Square(&t1)
   368  	}
   369  	t0.Multiply(&t1, &t0)     // 2^50 - 1
   370  	t1.Square(&t0)            // 2^51 - 2
   371  	for i := 1; i < 50; i++ { // 2^100 - 2^50
   372  		t1.Square(&t1)
   373  	}
   374  	t1.Multiply(&t1, &t0)      // 2^100 - 1
   375  	t2.Square(&t1)             // 2^101 - 2
   376  	for i := 1; i < 100; i++ { // 2^200 - 2^100
   377  		t2.Square(&t2)
   378  	}
   379  	t1.Multiply(&t2, &t1)     // 2^200 - 1
   380  	t1.Square(&t1)            // 2^201 - 2
   381  	for i := 1; i < 50; i++ { // 2^250 - 2^50
   382  		t1.Square(&t1)
   383  	}
   384  	t0.Multiply(&t1, &t0)     // 2^250 - 1
   385  	t0.Square(&t0)            // 2^251 - 2
   386  	t0.Square(&t0)            // 2^252 - 4
   387  	return v.Multiply(&t0, x) // 2^252 - 3 -> x^(2^252-3)
   388  }
   389  
   390  // sqrtM1 is 2^((p-1)/4), which squared is equal to -1 by Euler's Criterion.
   391  var sqrtM1 = &Element{1718705420411056, 234908883556509,
   392  	2233514472574048, 2117202627021982, 765476049583133}
   393  
   394  // SqrtRatio sets r to the non-negative square root of the ratio of u and v.
   395  //
   396  // If u/v is square, SqrtRatio returns r and 1. If u/v is not square, SqrtRatio
   397  // sets r according to Section 4.3 of draft-irtf-cfrg-ristretto255-decaf448-00,
   398  // and returns r and 0.
   399  func (r *Element) SqrtRatio(u, v *Element) (R *Element, wasSquare int) {
   400  	t0 := new(Element)
   401  
   402  	// r = (u * v3) * (u * v7)^((p-5)/8)
   403  	v2 := new(Element).Square(v)
   404  	uv3 := new(Element).Multiply(u, t0.Multiply(v2, v))
   405  	uv7 := new(Element).Multiply(uv3, t0.Square(v2))
   406  	rr := new(Element).Multiply(uv3, t0.Pow22523(uv7))
   407  
   408  	check := new(Element).Multiply(v, t0.Square(rr)) // check = v * r^2
   409  
   410  	uNeg := new(Element).Negate(u)
   411  	correctSignSqrt := check.Equal(u)
   412  	flippedSignSqrt := check.Equal(uNeg)
   413  	flippedSignSqrtI := check.Equal(t0.Multiply(uNeg, sqrtM1))
   414  
   415  	rPrime := new(Element).Multiply(rr, sqrtM1) // r_prime = SQRT_M1 * r
   416  	// r = CT_SELECT(r_prime IF flipped_sign_sqrt | flipped_sign_sqrt_i ELSE r)
   417  	rr.Select(rPrime, rr, flippedSignSqrt|flippedSignSqrtI)
   418  
   419  	r.Absolute(rr) // Choose the nonnegative square root.
   420  	return r, correctSignSqrt | flippedSignSqrt
   421  }
   422  

View as plain text