I am working on a cryptography implementation and part of the design includes the following:
( (y^a)^b / (y^c)^b ) mod p
I have the following snippet:
BigInteger yab = y.pow(ab.intValue());
BigInteger ycb = y.pow(cb.intValue());
BigInteger ans = (yab.divide(ycb)).mod(p);
It works fine for small integer. Once I replaced it with generated keys, the exponent grew so huge and I will hit the "BigInteger out of int range" error. I have tried the modPow function but the result is different.
I understand that casting it to int has its limitation. Does that means my implementation is infeasible?
It seems like you're doing modular arithmetic in group where n is a prime (in your case is n = p ). This means that
x / y
is not a division but a multiplication of x with the y -1 (modular inverse of y ).
Good thing is that the BigInteger class provides such a method:
BigInteger ans = yab.multiply(ycb.modInverse(p)).mod(p);
where yab
and ycb
can be efficiently computed without overflow (assuming ab
is the product of a
and b
):
BigInteger yab = y.modPow(ab, p);
BigInteger ycb = y.modPow(cb, p);
You can simplify the code and this will also make it faster
x^y / x^z = x^(y - z)
so
BigInteger yab = y.pow(ab.intValue());
BigInteger ycb = y.pow(cb.intValue());
BigInteger ans = (yab.divide(ycb)).mod(p);
can be simplified to
BigInteger yabc = y.pow((int) (ab.longValue() - cb.longValue()));
BigInteger ans = yabc.mod(p);
or
BigInteger and = y.modPow(ab.minus(cb), p);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.