...

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

Documentation: crypto/internal/edwards25519/field

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

View as plain text