github.com/dorkamotorka/go/src@v0.0.0-20230614113921-187095f0e316/crypto/internal/bigmod/nat.go (about) 1 // Copyright 2021 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 bigmod 6 7 import ( 8 "encoding/binary" 9 "errors" 10 "math/big" 11 "math/bits" 12 ) 13 14 const ( 15 // _W is the size in bits of our limbs. 16 _W = bits.UintSize 17 // _S is the size in bytes of our limbs. 18 _S = _W / 8 19 ) 20 21 // choice represents a constant-time boolean. The value of choice is always 22 // either 1 or 0. We use an int instead of bool in order to make decisions in 23 // constant time by turning it into a mask. 24 type choice uint 25 26 func not(c choice) choice { return 1 ^ c } 27 28 const yes = choice(1) 29 const no = choice(0) 30 31 // ctMask is all 1s if on is yes, and all 0s otherwise. 32 func ctMask(on choice) uint { return -uint(on) } 33 34 // ctEq returns 1 if x == y, and 0 otherwise. The execution time of this 35 // function does not depend on its inputs. 36 func ctEq(x, y uint) choice { 37 // If x != y, then either x - y or y - x will generate a carry. 38 _, c1 := bits.Sub(x, y, 0) 39 _, c2 := bits.Sub(y, x, 0) 40 return not(choice(c1 | c2)) 41 } 42 43 // ctGeq returns 1 if x >= y, and 0 otherwise. The execution time of this 44 // function does not depend on its inputs. 45 func ctGeq(x, y uint) choice { 46 // If x < y, then x - y generates a carry. 47 _, carry := bits.Sub(x, y, 0) 48 return not(choice(carry)) 49 } 50 51 // Nat represents an arbitrary natural number 52 // 53 // Each Nat has an announced length, which is the number of limbs it has stored. 54 // Operations on this number are allowed to leak this length, but will not leak 55 // any information about the values contained in those limbs. 56 type Nat struct { 57 // limbs is little-endian in base 2^W with W = bits.UintSize. 58 limbs []uint 59 } 60 61 // preallocTarget is the size in bits of the numbers used to implement the most 62 // common and most performant RSA key size. It's also enough to cover some of 63 // the operations of key sizes up to 4096. 64 const preallocTarget = 2048 65 const preallocLimbs = (preallocTarget + _W - 1) / _W 66 67 // NewNat returns a new nat with a size of zero, just like new(Nat), but with 68 // the preallocated capacity to hold a number of up to preallocTarget bits. 69 // NewNat inlines, so the allocation can live on the stack. 70 func NewNat() *Nat { 71 limbs := make([]uint, 0, preallocLimbs) 72 return &Nat{limbs} 73 } 74 75 // expand expands x to n limbs, leaving its value unchanged. 76 func (x *Nat) expand(n int) *Nat { 77 if len(x.limbs) > n { 78 panic("bigmod: internal error: shrinking nat") 79 } 80 if cap(x.limbs) < n { 81 newLimbs := make([]uint, n) 82 copy(newLimbs, x.limbs) 83 x.limbs = newLimbs 84 return x 85 } 86 extraLimbs := x.limbs[len(x.limbs):n] 87 for i := range extraLimbs { 88 extraLimbs[i] = 0 89 } 90 x.limbs = x.limbs[:n] 91 return x 92 } 93 94 // reset returns a zero nat of n limbs, reusing x's storage if n <= cap(x.limbs). 95 func (x *Nat) reset(n int) *Nat { 96 if cap(x.limbs) < n { 97 x.limbs = make([]uint, n) 98 return x 99 } 100 for i := range x.limbs { 101 x.limbs[i] = 0 102 } 103 x.limbs = x.limbs[:n] 104 return x 105 } 106 107 // set assigns x = y, optionally resizing x to the appropriate size. 108 func (x *Nat) set(y *Nat) *Nat { 109 x.reset(len(y.limbs)) 110 copy(x.limbs, y.limbs) 111 return x 112 } 113 114 // setBig assigns x = n, optionally resizing n to the appropriate size. 115 // 116 // The announced length of x is set based on the actual bit size of the input, 117 // ignoring leading zeroes. 118 func (x *Nat) setBig(n *big.Int) *Nat { 119 limbs := n.Bits() 120 x.reset(len(limbs)) 121 for i := range limbs { 122 x.limbs[i] = uint(limbs[i]) 123 } 124 return x 125 } 126 127 // Bytes returns x as a zero-extended big-endian byte slice. The size of the 128 // slice will match the size of m. 129 // 130 // x must have the same size as m and it must be reduced modulo m. 131 func (x *Nat) Bytes(m *Modulus) []byte { 132 i := m.Size() 133 bytes := make([]byte, i) 134 for _, limb := range x.limbs { 135 for j := 0; j < _S; j++ { 136 i-- 137 if i < 0 { 138 if limb == 0 { 139 break 140 } 141 panic("bigmod: modulus is smaller than nat") 142 } 143 bytes[i] = byte(limb) 144 limb >>= 8 145 } 146 } 147 return bytes 148 } 149 150 // SetBytes assigns x = b, where b is a slice of big-endian bytes. 151 // SetBytes returns an error if b >= m. 152 // 153 // The output will be resized to the size of m and overwritten. 154 func (x *Nat) SetBytes(b []byte, m *Modulus) (*Nat, error) { 155 if err := x.setBytes(b, m); err != nil { 156 return nil, err 157 } 158 if x.cmpGeq(m.nat) == yes { 159 return nil, errors.New("input overflows the modulus") 160 } 161 return x, nil 162 } 163 164 // SetOverflowingBytes assigns x = b, where b is a slice of big-endian bytes. 165 // SetOverflowingBytes returns an error if b has a longer bit length than m, but 166 // reduces overflowing values up to 2^⌈log2(m)⌉ - 1. 167 // 168 // The output will be resized to the size of m and overwritten. 169 func (x *Nat) SetOverflowingBytes(b []byte, m *Modulus) (*Nat, error) { 170 if err := x.setBytes(b, m); err != nil { 171 return nil, err 172 } 173 leading := _W - bitLen(x.limbs[len(x.limbs)-1]) 174 if leading < m.leading { 175 return nil, errors.New("input overflows the modulus size") 176 } 177 x.maybeSubtractModulus(no, m) 178 return x, nil 179 } 180 181 // bigEndianUint returns the contents of buf interpreted as a 182 // big-endian encoded uint value. 183 func bigEndianUint(buf []byte) uint { 184 if _W == 64 { 185 return uint(binary.BigEndian.Uint64(buf)) 186 } 187 return uint(binary.BigEndian.Uint32(buf)) 188 } 189 190 func (x *Nat) setBytes(b []byte, m *Modulus) error { 191 x.resetFor(m) 192 i, k := len(b), 0 193 for k < len(x.limbs) && i >= _S { 194 x.limbs[k] = bigEndianUint(b[i-_S : i]) 195 i -= _S 196 k++ 197 } 198 for s := 0; s < _W && k < len(x.limbs) && i > 0; s += 8 { 199 x.limbs[k] |= uint(b[i-1]) << s 200 i-- 201 } 202 if i > 0 { 203 return errors.New("input overflows the modulus size") 204 } 205 return nil 206 } 207 208 // Equal returns 1 if x == y, and 0 otherwise. 209 // 210 // Both operands must have the same announced length. 211 func (x *Nat) Equal(y *Nat) choice { 212 // Eliminate bounds checks in the loop. 213 size := len(x.limbs) 214 xLimbs := x.limbs[:size] 215 yLimbs := y.limbs[:size] 216 217 equal := yes 218 for i := 0; i < size; i++ { 219 equal &= ctEq(xLimbs[i], yLimbs[i]) 220 } 221 return equal 222 } 223 224 // IsZero returns 1 if x == 0, and 0 otherwise. 225 func (x *Nat) IsZero() choice { 226 // Eliminate bounds checks in the loop. 227 size := len(x.limbs) 228 xLimbs := x.limbs[:size] 229 230 zero := yes 231 for i := 0; i < size; i++ { 232 zero &= ctEq(xLimbs[i], 0) 233 } 234 return zero 235 } 236 237 // cmpGeq returns 1 if x >= y, and 0 otherwise. 238 // 239 // Both operands must have the same announced length. 240 func (x *Nat) cmpGeq(y *Nat) choice { 241 // Eliminate bounds checks in the loop. 242 size := len(x.limbs) 243 xLimbs := x.limbs[:size] 244 yLimbs := y.limbs[:size] 245 246 var c uint 247 for i := 0; i < size; i++ { 248 _, c = bits.Sub(xLimbs[i], yLimbs[i], c) 249 } 250 // If there was a carry, then subtracting y underflowed, so 251 // x is not greater than or equal to y. 252 return not(choice(c)) 253 } 254 255 // assign sets x <- y if on == 1, and does nothing otherwise. 256 // 257 // Both operands must have the same announced length. 258 func (x *Nat) assign(on choice, y *Nat) *Nat { 259 // Eliminate bounds checks in the loop. 260 size := len(x.limbs) 261 xLimbs := x.limbs[:size] 262 yLimbs := y.limbs[:size] 263 264 mask := ctMask(on) 265 for i := 0; i < size; i++ { 266 xLimbs[i] ^= mask & (xLimbs[i] ^ yLimbs[i]) 267 } 268 return x 269 } 270 271 // add computes x += y and returns the carry. 272 // 273 // Both operands must have the same announced length. 274 func (x *Nat) add(y *Nat) (c uint) { 275 // Eliminate bounds checks in the loop. 276 size := len(x.limbs) 277 xLimbs := x.limbs[:size] 278 yLimbs := y.limbs[:size] 279 280 for i := 0; i < size; i++ { 281 xLimbs[i], c = bits.Add(xLimbs[i], yLimbs[i], c) 282 } 283 return 284 } 285 286 // sub computes x -= y. It returns the borrow of the subtraction. 287 // 288 // Both operands must have the same announced length. 289 func (x *Nat) sub(y *Nat) (c uint) { 290 // Eliminate bounds checks in the loop. 291 size := len(x.limbs) 292 xLimbs := x.limbs[:size] 293 yLimbs := y.limbs[:size] 294 295 for i := 0; i < size; i++ { 296 xLimbs[i], c = bits.Sub(xLimbs[i], yLimbs[i], c) 297 } 298 return 299 } 300 301 // Modulus is used for modular arithmetic, precomputing relevant constants. 302 // 303 // Moduli are assumed to be odd numbers. Moduli can also leak the exact 304 // number of bits needed to store their value, and are stored without padding. 305 // 306 // Their actual value is still kept secret. 307 type Modulus struct { 308 // The underlying natural number for this modulus. 309 // 310 // This will be stored without any padding, and shouldn't alias with any 311 // other natural number being used. 312 nat *Nat 313 leading int // number of leading zeros in the modulus 314 m0inv uint // -nat.limbs[0]⁻¹ mod _W 315 rr *Nat // R*R for montgomeryRepresentation 316 } 317 318 // rr returns R*R with R = 2^(_W * n) and n = len(m.nat.limbs). 319 func rr(m *Modulus) *Nat { 320 rr := NewNat().ExpandFor(m) 321 // R*R is 2^(2 * _W * n). We can safely get 2^(_W * (n - 1)) by setting the 322 // most significant limb to 1. We then get to R*R by shifting left by _W 323 // n + 1 times. 324 n := len(rr.limbs) 325 rr.limbs[n-1] = 1 326 for i := n - 1; i < 2*n; i++ { 327 rr.shiftIn(0, m) // x = x * 2^_W mod m 328 } 329 return rr 330 } 331 332 // minusInverseModW computes -x⁻¹ mod _W with x odd. 333 // 334 // This operation is used to precompute a constant involved in Montgomery 335 // multiplication. 336 func minusInverseModW(x uint) uint { 337 // Every iteration of this loop doubles the least-significant bits of 338 // correct inverse in y. The first three bits are already correct (1⁻¹ = 1, 339 // 3⁻¹ = 3, 5⁻¹ = 5, and 7⁻¹ = 7 mod 8), so doubling five times is enough 340 // for 64 bits (and wastes only one iteration for 32 bits). 341 // 342 // See https://crypto.stackexchange.com/a/47496. 343 y := x 344 for i := 0; i < 5; i++ { 345 y = y * (2 - x*y) 346 } 347 return -y 348 } 349 350 // NewModulusFromBig creates a new Modulus from a [big.Int]. 351 // 352 // The Int must be odd. The number of significant bits (and nothing else) is 353 // leaked through timing side-channels. 354 func NewModulusFromBig(n *big.Int) (*Modulus, error) { 355 if b := n.Bits(); len(b) == 0 { 356 return nil, errors.New("modulus must be >= 0") 357 } else if b[0]&1 != 1 { 358 return nil, errors.New("modulus must be odd") 359 } 360 m := &Modulus{} 361 m.nat = NewNat().setBig(n) 362 m.leading = _W - bitLen(m.nat.limbs[len(m.nat.limbs)-1]) 363 m.m0inv = minusInverseModW(m.nat.limbs[0]) 364 m.rr = rr(m) 365 return m, nil 366 } 367 368 // bitLen is a version of bits.Len that only leaks the bit length of n, but not 369 // its value. bits.Len and bits.LeadingZeros use a lookup table for the 370 // low-order bits on some architectures. 371 func bitLen(n uint) int { 372 var len int 373 // We assume, here and elsewhere, that comparison to zero is constant time 374 // with respect to different non-zero values. 375 for n != 0 { 376 len++ 377 n >>= 1 378 } 379 return len 380 } 381 382 // Size returns the size of m in bytes. 383 func (m *Modulus) Size() int { 384 return (m.BitLen() + 7) / 8 385 } 386 387 // BitLen returns the size of m in bits. 388 func (m *Modulus) BitLen() int { 389 return len(m.nat.limbs)*_W - int(m.leading) 390 } 391 392 // Nat returns m as a Nat. The return value must not be written to. 393 func (m *Modulus) Nat() *Nat { 394 return m.nat 395 } 396 397 // shiftIn calculates x = x << _W + y mod m. 398 // 399 // This assumes that x is already reduced mod m. 400 func (x *Nat) shiftIn(y uint, m *Modulus) *Nat { 401 d := NewNat().resetFor(m) 402 403 // Eliminate bounds checks in the loop. 404 size := len(m.nat.limbs) 405 xLimbs := x.limbs[:size] 406 dLimbs := d.limbs[:size] 407 mLimbs := m.nat.limbs[:size] 408 409 // Each iteration of this loop computes x = 2x + b mod m, where b is a bit 410 // from y. Effectively, it left-shifts x and adds y one bit at a time, 411 // reducing it every time. 412 // 413 // To do the reduction, each iteration computes both 2x + b and 2x + b - m. 414 // The next iteration (and finally the return line) will use either result 415 // based on whether 2x + b overflows m. 416 needSubtraction := no 417 for i := _W - 1; i >= 0; i-- { 418 carry := (y >> i) & 1 419 var borrow uint 420 mask := ctMask(needSubtraction) 421 for i := 0; i < size; i++ { 422 l := xLimbs[i] ^ (mask & (xLimbs[i] ^ dLimbs[i])) 423 xLimbs[i], carry = bits.Add(l, l, carry) 424 dLimbs[i], borrow = bits.Sub(xLimbs[i], mLimbs[i], borrow) 425 } 426 // Like in maybeSubtractModulus, we need the subtraction if either it 427 // didn't underflow (meaning 2x + b > m) or if computing 2x + b 428 // overflowed (meaning 2x + b > 2^_W*n > m). 429 needSubtraction = not(choice(borrow)) | choice(carry) 430 } 431 return x.assign(needSubtraction, d) 432 } 433 434 // Mod calculates out = x mod m. 435 // 436 // This works regardless how large the value of x is. 437 // 438 // The output will be resized to the size of m and overwritten. 439 func (out *Nat) Mod(x *Nat, m *Modulus) *Nat { 440 out.resetFor(m) 441 // Working our way from the most significant to the least significant limb, 442 // we can insert each limb at the least significant position, shifting all 443 // previous limbs left by _W. This way each limb will get shifted by the 444 // correct number of bits. We can insert at least N - 1 limbs without 445 // overflowing m. After that, we need to reduce every time we shift. 446 i := len(x.limbs) - 1 447 // For the first N - 1 limbs we can skip the actual shifting and position 448 // them at the shifted position, which starts at min(N - 2, i). 449 start := len(m.nat.limbs) - 2 450 if i < start { 451 start = i 452 } 453 for j := start; j >= 0; j-- { 454 out.limbs[j] = x.limbs[i] 455 i-- 456 } 457 // We shift in the remaining limbs, reducing modulo m each time. 458 for i >= 0 { 459 out.shiftIn(x.limbs[i], m) 460 i-- 461 } 462 return out 463 } 464 465 // ExpandFor ensures x has the right size to work with operations modulo m. 466 // 467 // The announced size of x must be smaller than or equal to that of m. 468 func (x *Nat) ExpandFor(m *Modulus) *Nat { 469 return x.expand(len(m.nat.limbs)) 470 } 471 472 // resetFor ensures out has the right size to work with operations modulo m. 473 // 474 // out is zeroed and may start at any size. 475 func (out *Nat) resetFor(m *Modulus) *Nat { 476 return out.reset(len(m.nat.limbs)) 477 } 478 479 // maybeSubtractModulus computes x -= m if and only if x >= m or if "always" is yes. 480 // 481 // It can be used to reduce modulo m a value up to 2m - 1, which is a common 482 // range for results computed by higher level operations. 483 // 484 // always is usually a carry that indicates that the operation that produced x 485 // overflowed its size, meaning abstractly x > 2^_W*n > m even if x < m. 486 // 487 // x and m operands must have the same announced length. 488 func (x *Nat) maybeSubtractModulus(always choice, m *Modulus) { 489 t := NewNat().set(x) 490 underflow := t.sub(m.nat) 491 // We keep the result if x - m didn't underflow (meaning x >= m) 492 // or if always was set. 493 keep := not(choice(underflow)) | choice(always) 494 x.assign(keep, t) 495 } 496 497 // Sub computes x = x - y mod m. 498 // 499 // The length of both operands must be the same as the modulus. Both operands 500 // must already be reduced modulo m. 501 func (x *Nat) Sub(y *Nat, m *Modulus) *Nat { 502 underflow := x.sub(y) 503 // If the subtraction underflowed, add m. 504 t := NewNat().set(x) 505 t.add(m.nat) 506 x.assign(choice(underflow), t) 507 return x 508 } 509 510 // Add computes x = x + y mod m. 511 // 512 // The length of both operands must be the same as the modulus. Both operands 513 // must already be reduced modulo m. 514 func (x *Nat) Add(y *Nat, m *Modulus) *Nat { 515 overflow := x.add(y) 516 x.maybeSubtractModulus(choice(overflow), m) 517 return x 518 } 519 520 // montgomeryRepresentation calculates x = x * R mod m, with R = 2^(_W * n) and 521 // n = len(m.nat.limbs). 522 // 523 // Faster Montgomery multiplication replaces standard modular multiplication for 524 // numbers in this representation. 525 // 526 // This assumes that x is already reduced mod m. 527 func (x *Nat) montgomeryRepresentation(m *Modulus) *Nat { 528 // A Montgomery multiplication (which computes a * b / R) by R * R works out 529 // to a multiplication by R, which takes the value out of the Montgomery domain. 530 return x.montgomeryMul(x, m.rr, m) 531 } 532 533 // montgomeryReduction calculates x = x / R mod m, with R = 2^(_W * n) and 534 // n = len(m.nat.limbs). 535 // 536 // This assumes that x is already reduced mod m. 537 func (x *Nat) montgomeryReduction(m *Modulus) *Nat { 538 // By Montgomery multiplying with 1 not in Montgomery representation, we 539 // convert out back from Montgomery representation, because it works out to 540 // dividing by R. 541 one := NewNat().ExpandFor(m) 542 one.limbs[0] = 1 543 return x.montgomeryMul(x, one, m) 544 } 545 546 // montgomeryMul calculates x = a * b / R mod m, with R = 2^(_W * n) and 547 // n = len(m.nat.limbs), also known as a Montgomery multiplication. 548 // 549 // All inputs should be the same length and already reduced modulo m. 550 // x will be resized to the size of m and overwritten. 551 func (x *Nat) montgomeryMul(a *Nat, b *Nat, m *Modulus) *Nat { 552 n := len(m.nat.limbs) 553 mLimbs := m.nat.limbs[:n] 554 aLimbs := a.limbs[:n] 555 bLimbs := b.limbs[:n] 556 557 switch n { 558 default: 559 // Attempt to use a stack-allocated backing array. 560 T := make([]uint, 0, preallocLimbs*2) 561 if cap(T) < n*2 { 562 T = make([]uint, 0, n*2) 563 } 564 T = T[:n*2] 565 566 // This loop implements Word-by-Word Montgomery Multiplication, as 567 // described in Algorithm 4 (Fig. 3) of "Efficient Software 568 // Implementations of Modular Exponentiation" by Shay Gueron 569 // [https://eprint.iacr.org/2011/239.pdf]. 570 var c uint 571 for i := 0; i < n; i++ { 572 _ = T[n+i] // bounds check elimination hint 573 574 // Step 1 (T = a × b) is computed as a large pen-and-paper column 575 // multiplication of two numbers with n base-2^_W digits. If we just 576 // wanted to produce 2n-wide T, we would do 577 // 578 // for i := 0; i < n; i++ { 579 // d := bLimbs[i] 580 // T[n+i] = addMulVVW(T[i:n+i], aLimbs, d) 581 // } 582 // 583 // where d is a digit of the multiplier, T[i:n+i] is the shifted 584 // position of the product of that digit, and T[n+i] is the final carry. 585 // Note that T[i] isn't modified after processing the i-th digit. 586 // 587 // Instead of running two loops, one for Step 1 and one for Steps 2–6, 588 // the result of Step 1 is computed during the next loop. This is 589 // possible because each iteration only uses T[i] in Step 2 and then 590 // discards it in Step 6. 591 d := bLimbs[i] 592 c1 := addMulVVW(T[i:n+i], aLimbs, d) 593 594 // Step 6 is replaced by shifting the virtual window we operate 595 // over: T of the algorithm is T[i:] for us. That means that T1 in 596 // Step 2 (T mod 2^_W) is simply T[i]. k0 in Step 3 is our m0inv. 597 Y := T[i] * m.m0inv 598 599 // Step 4 and 5 add Y × m to T, which as mentioned above is stored 600 // at T[i:]. The two carries (from a × d and Y × m) are added up in 601 // the next word T[n+i], and the carry bit from that addition is 602 // brought forward to the next iteration. 603 c2 := addMulVVW(T[i:n+i], mLimbs, Y) 604 T[n+i], c = bits.Add(c1, c2, c) 605 } 606 607 // Finally for Step 7 we copy the final T window into x, and subtract m 608 // if necessary (which as explained in maybeSubtractModulus can be the 609 // case both if x >= m, or if x overflowed). 610 // 611 // The paper suggests in Section 4 that we can do an "Almost Montgomery 612 // Multiplication" by subtracting only in the overflow case, but the 613 // cost is very similar since the constant time subtraction tells us if 614 // x >= m as a side effect, and taking care of the broken invariant is 615 // highly undesirable (see https://go.dev/issue/13907). 616 copy(x.reset(n).limbs, T[n:]) 617 x.maybeSubtractModulus(choice(c), m) 618 619 // The following specialized cases follow the exact same algorithm, but 620 // optimized for the sizes most used in RSA. addMulVVW is implemented in 621 // assembly with loop unrolling depending on the architecture and bounds 622 // checks are removed by the compiler thanks to the constant size. 623 case 1024 / _W: 624 const n = 1024 / _W // compiler hint 625 T := make([]uint, n*2) 626 var c uint 627 for i := 0; i < n; i++ { 628 d := bLimbs[i] 629 c1 := addMulVVW1024(&T[i], &aLimbs[0], d) 630 Y := T[i] * m.m0inv 631 c2 := addMulVVW1024(&T[i], &mLimbs[0], Y) 632 T[n+i], c = bits.Add(c1, c2, c) 633 } 634 copy(x.reset(n).limbs, T[n:]) 635 x.maybeSubtractModulus(choice(c), m) 636 637 case 1536 / _W: 638 const n = 1536 / _W // compiler hint 639 T := make([]uint, n*2) 640 var c uint 641 for i := 0; i < n; i++ { 642 d := bLimbs[i] 643 c1 := addMulVVW1536(&T[i], &aLimbs[0], d) 644 Y := T[i] * m.m0inv 645 c2 := addMulVVW1536(&T[i], &mLimbs[0], Y) 646 T[n+i], c = bits.Add(c1, c2, c) 647 } 648 copy(x.reset(n).limbs, T[n:]) 649 x.maybeSubtractModulus(choice(c), m) 650 651 case 2048 / _W: 652 const n = 2048 / _W // compiler hint 653 T := make([]uint, n*2) 654 var c uint 655 for i := 0; i < n; i++ { 656 d := bLimbs[i] 657 c1 := addMulVVW2048(&T[i], &aLimbs[0], d) 658 Y := T[i] * m.m0inv 659 c2 := addMulVVW2048(&T[i], &mLimbs[0], Y) 660 T[n+i], c = bits.Add(c1, c2, c) 661 } 662 copy(x.reset(n).limbs, T[n:]) 663 x.maybeSubtractModulus(choice(c), m) 664 } 665 666 return x 667 } 668 669 // addMulVVW multiplies the multi-word value x by the single-word value y, 670 // adding the result to the multi-word value z and returning the final carry. 671 // It can be thought of as one row of a pen-and-paper column multiplication. 672 func addMulVVW(z, x []uint, y uint) (carry uint) { 673 _ = x[len(z)-1] // bounds check elimination hint 674 for i := range z { 675 hi, lo := bits.Mul(x[i], y) 676 lo, c := bits.Add(lo, z[i], 0) 677 // We use bits.Add with zero to get an add-with-carry instruction that 678 // absorbs the carry from the previous bits.Add. 679 hi, _ = bits.Add(hi, 0, c) 680 lo, c = bits.Add(lo, carry, 0) 681 hi, _ = bits.Add(hi, 0, c) 682 carry = hi 683 z[i] = lo 684 } 685 return carry 686 } 687 688 // Mul calculates x = x * y mod m. 689 // 690 // The length of both operands must be the same as the modulus. Both operands 691 // must already be reduced modulo m. 692 func (x *Nat) Mul(y *Nat, m *Modulus) *Nat { 693 // A Montgomery multiplication by a value out of the Montgomery domain 694 // takes the result out of Montgomery representation. 695 xR := NewNat().set(x).montgomeryRepresentation(m) // xR = x * R mod m 696 return x.montgomeryMul(xR, y, m) // x = xR * y / R mod m 697 } 698 699 // Exp calculates out = x^e mod m. 700 // 701 // The exponent e is represented in big-endian order. The output will be resized 702 // to the size of m and overwritten. x must already be reduced modulo m. 703 func (out *Nat) Exp(x *Nat, e []byte, m *Modulus) *Nat { 704 // We use a 4 bit window. For our RSA workload, 4 bit windows are faster 705 // than 2 bit windows, but use an extra 12 nats worth of scratch space. 706 // Using bit sizes that don't divide 8 are more complex to implement, but 707 // are likely to be more efficient if necessary. 708 709 table := [(1 << 4) - 1]*Nat{ // table[i] = x ^ (i+1) 710 // newNat calls are unrolled so they are allocated on the stack. 711 NewNat(), NewNat(), NewNat(), NewNat(), NewNat(), 712 NewNat(), NewNat(), NewNat(), NewNat(), NewNat(), 713 NewNat(), NewNat(), NewNat(), NewNat(), NewNat(), 714 } 715 table[0].set(x).montgomeryRepresentation(m) 716 for i := 1; i < len(table); i++ { 717 table[i].montgomeryMul(table[i-1], table[0], m) 718 } 719 720 out.resetFor(m) 721 out.limbs[0] = 1 722 out.montgomeryRepresentation(m) 723 tmp := NewNat().ExpandFor(m) 724 for _, b := range e { 725 for _, j := range []int{4, 0} { 726 // Square four times. Optimization note: this can be implemented 727 // more efficiently than with generic Montgomery multiplication. 728 out.montgomeryMul(out, out, m) 729 out.montgomeryMul(out, out, m) 730 out.montgomeryMul(out, out, m) 731 out.montgomeryMul(out, out, m) 732 733 // Select x^k in constant time from the table. 734 k := uint((b >> j) & 0b1111) 735 for i := range table { 736 tmp.assign(ctEq(k, uint(i+1)), table[i]) 737 } 738 739 // Multiply by x^k, discarding the result if k = 0. 740 tmp.montgomeryMul(out, tmp, m) 741 out.assign(not(ctEq(k, 0)), tmp) 742 } 743 } 744 745 return out.montgomeryReduction(m) 746 } 747 748 // ExpShort calculates out = x^e mod m. 749 // 750 // The output will be resized to the size of m and overwritten. x must already 751 // be reduced modulo m. This leaks the exact bit size of the exponent. 752 func (out *Nat) ExpShort(x *Nat, e uint, m *Modulus) *Nat { 753 xR := NewNat().set(x).montgomeryRepresentation(m) 754 755 out.resetFor(m) 756 out.limbs[0] = 1 757 out.montgomeryRepresentation(m) 758 759 // For short exponents, precomputing a table and using a window like in Exp 760 // doesn't pay off. Instead, we do a simple constant-time conditional 761 // square-and-multiply chain, skipping the initial run of zeroes. 762 tmp := NewNat().ExpandFor(m) 763 for i := bits.UintSize - bitLen(e); i < bits.UintSize; i++ { 764 out.montgomeryMul(out, out, m) 765 k := (e >> (bits.UintSize - i - 1)) & 1 766 tmp.montgomeryMul(out, xR, m) 767 out.assign(ctEq(k, 1), tmp) 768 } 769 return out.montgomeryReduction(m) 770 }