[英]Java pow BigInteger implementation
I am working on a cryptography implementation and part of the design includes the following: 我正在研究密码学实现,部分设计包括以下内容:
( (y^a)^b / (y^c)^b ) mod p ((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.
一旦用生成的键替换了它,指数就变得如此巨大,并且我将遇到“ BigInteger int range out”错误。 I have tried the modPow function but the result is different.
我尝试了modPow函数,但结果不同。
I understand that casting it to int has its limitation. 我知道将其强制转换为int有其局限性。 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 ).
其中n是素数(在您的情况下为n = p )。 This means that
这意味着
x / y
is not a division but a multiplication of x with the y -1 (modular inverse of y ). 是不是一个分裂但x的与y -1(Y模块化倒数)相乘。
Good thing is that the BigInteger class provides such a method: 好东西是BigInteger类提供了这样一种方法:
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
): 其中
yab
和ycb
可以有效地计算而不会溢出(假设ab
是a
和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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.