Test modular exponentiation with BN254 and BLS12-381 moduli

This commit is contained in:
Mamy André-Ratsimbazafy 2020-02-22 16:56:04 +01:00
parent 24f2e1088e
commit e0f4e49cb5
No known key found for this signature in database
GPG Key ID: 7B88AD1FE79492E1
3 changed files with 23 additions and 2 deletions

View File

@ -399,7 +399,7 @@ func nativeEndianToHex(bytes: openarray[byte], order: static[Endianness]): strin
# #
# ############################################################ # ############################################################
func fromHex*(T: type BigInt, s: string): T = func fromHex*(T: type BigInt, s: string): T {.noInit.} =
## Convert a hex string to BigInt that can hold ## Convert a hex string to BigInt that can hold
## the specified number of bits ## the specified number of bits
## ##

View File

@ -25,7 +25,7 @@ func fromUint*(dst: var Fq,
src: SomeUnsignedInt) = src: SomeUnsignedInt) =
## Parse a regular unsigned integer ## Parse a regular unsigned integer
## and store it into a BigInt of size `bits` ## and store it into a BigInt of size `bits`
let raw = (type dst.mres).fromRawUint(cast[array[sizeof(src), byte]](src), cpuEndian) let raw {.noinit.} = (type dst.mres).fromRawUint(cast[array[sizeof(src), byte]](src), cpuEndian)
dst.fromBig(raw) dst.fromBig(raw)
func exportRawUint*(dst: var openarray[byte], func exportRawUint*(dst: var openarray[byte],
@ -52,3 +52,8 @@ func toHex*(f: Fq, order: static Endianness = bigEndian): string =
## CT: ## CT:
## - no leaks ## - no leaks
result = f.toBig().toHex(order) result = f.toBig().toHex(order)
func fromHex*(dst: var Fq, s: string) {.raises: [ValueError].}=
## Convert a hex string to a element of Fq
let raw {.noinit.} = fromHex(dst.mres.typeof, s)
dst.fromBig(raw)

View File

@ -92,4 +92,20 @@ proc main() =
# Check equality when converting back to natural domain # Check equality when converting back to natural domain
20'u64 == r 20'u64 == r
test "x^(p-2) mod p (modular inversion if p prime)":
var x: Fq[BLS12_381]
# BN254 field modulus
x.fromHex("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47")
# BLS12-381 prime - 2
let exponent = BigInt[381].fromHex("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaa9")
let expected = "0x0636759a0f3034fa47174b2c0334902f11e9915b7bd89c6a2b3082b109abbc9837da17201f6d8286fe6203caa1b9d4c8"
x.pow(exponent)
let computed = x.toHex()
check:
computed == expected
main() main()