Scoop API

scoop:scoop.math:0.1.0

src/internal/integer/montgomery.scoop

Selected production source · src/internal/integer/montgomery.scoop

1package scoop.math
3// REDC with an odd modulus. Every operand and result is in [0, modulus).
4private fun montgomeryMultiply(a: Array<UInt>, b: Array<UInt>, modulus: Array<UInt>, inverse: UInt): Array<UInt> {
5 val n = modulus.size
6 val words = MutableArray<UInt>(addExact(multiplyExact(n, 2L), 1L)) { _ -> 0u }
7 var i = 0L
8 while (i < a.size) {
9 var carry = 0uL
10 var j = 0L
11 while (j < b.size) {
12 val product = a[i].toULong() * b[j].toULong() + words[i + j].toULong() + carry
13 words[i + j] = product.toUInt()
14 carry = product shr 32L
15 j += 1L
16 }
17 words[i + b.size] = carry.toUInt()
18 i += 1L
19 }
20 i = 0L
21 while (i < n) {
22 val multiplier = words[i] * inverse
23 var carry = 0uL
24 var j = 0L
25 while (j < n) {
26 val product = multiplier.toULong() * modulus[j].toULong() + words[i + j].toULong() + carry
27 words[i + j] = product.toUInt()
28 carry = product shr 32L
29 j += 1L
30 }
31 var position = i + n
32 while (carry != 0uL) {
33 val sum = words[position].toULong() + carry
34 words[position] = sum.toUInt()
35 carry = sum shr 32L
36 position += 1L
37 }
38 i += 1L
39 }
40 val result = magnitudeSnapshot(Array<UInt>(n + 1L) { index -> words[index + n] })
41 return if (magnitudeCompare(result, modulus) >= 0L) magnitudeSubtract(result, modulus) else result
44internal fun integerMontgomeryPow(base: IntegerStorage, exponent: Array<UInt>, modulus: IntegerStorage): IntegerStorage {
45 val divisor = integerMagnitude(modulus)
46 var reciprocal = 1u
47 var iteration = 0
48 while (iteration < 5) { reciprocal *= 2u - divisor[0L] * reciprocal; iteration += 1 }
49 val inverse = 0u - reciprocal
50 val radixBits = multiplyExact(divisor.size, 32L)
51 var result = integerMagnitude(integerMod(integerShift(IntegerStorage.Small(1L), radixBits, true), modulus))
52 val power = integerMagnitude(integerMod(integerShift(base, radixBits, true), modulus))
53 var bit = magnitudeBits(exponent)
54 while (bit > 0L) {
55 bit -= 1L
56 result = montgomeryMultiply(result, result, divisor, inverse)
57 if ((exponent[bit / 32L] and (1u shl (bit % 32L))) != 0u) result = montgomeryMultiply(result, power, divisor, inverse)
58 }
59 return integerFromMagnitude(false, montgomeryMultiply(result, Array<UInt>(1L) { _ -> 1u }, divisor, inverse))