Skip to content

bug: ModularBigInteger.pow(exponent: ModularBigInteger) allows incorrect usage and might produce false results! #336

@manfredscheucher

Description

@manfredscheucher

Describe the bug
The ModularBigInteger.pow(exponent: ModularBigInteger) function can be abused with an invalid modulus and might give false results!

More specifically, ModularBigInteger(residue=a,modulus=n).pow(ModularBigInteger(residue=b,modulus=m)) can only give the right result if m equals the order a modulo n. If you for example want to compute $2^{(-1)} = 4 mod 7$ (a=2,n=7,b=-1,m=2) but implicitly it converts (-1 mod 2) to (+1 mod 2) and you get $2^{(+1)} = 2 mod 7$ - which is obviously a distinct result. Here's another example: with a=2,n=7,b=3,m=2, the computation 2^3=8=1 mod 7 would become 2^1=2 mod 7 (3=1 mod 2), which is again wrong, and there is an infinite number of further examples.

Solution: Computing the order (or Euler phi function, prime factors,...) during run-time is a bad idea, but
my suggestion: Add annotations in the source code to inform the user that this must be provided. When programmers use this function, they should know what they are doing. Otherwise, they should not use it.


import com.ionspin.kotlin.bignum.integer.BigInteger
import com.ionspin.kotlin.bignum.modular.ModularBigInteger

val a = BigInteger(2)
val n = BigInteger(7)
val b = BigInteger(3)
val m = BigInteger(2)

val a_mod_n = ModularBigInteger.creatorForModulo(n).fromBigInteger(a)
val b_mod_m = ModularBigInteger.creatorForModulo(m).fromBigInteger(b)

println("correct:"+(a_mod_n.pow(b))) // correct
println("wrong  :"+(a_mod_n.pow(b_mod_m)))  // wrong

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions