简体   繁体   English

负数的BigInteger取幂

[英]BigInteger exponentiation with negative number

How can I do the same as in this python (using sage) code: 我该怎么做与此Python(使用鼠尾草)代码相同:

def elGamalDecrypt(c1, c2, p, x):
    return Mod(c2*c1^(-x),p)

with standard Java 7 libraries? 标准的Java 7库? All numbers are BigInteger . 所有数字均为BigInteger

I've tried a lot with no avail. 我已经尝试了很多无济于事。 In Python it's really simple and FAST. 在Python中,它非常简单且快速。

The BigInteger class in Java 7 has a modPow method, which handles modular exponentiation. Java 7中的BigInteger类具有一个modPow方法,该方法可处理模块化幂运算。 So, something like the following should work (although I haven't tested it): 因此,类似以下的内容应该可以工作(尽管我还没有测试过):

c2.multiply(c1.modPow(x.negate(), p)).mod(p)

The modPow method will only accept a negative exponent -x if c1 and p are coprime. 如果c1p为互质数,则modPow方法仅接受负指数-x (The name p suggests that p is prime, and if c1 and p aren't coprime, c1 would be divisible by p , and hence the exponentiation would make no sense, so I suspect that this won't be a problem.) (名称p表示p是质数,如果c1p不是互质数,则c1将被p整除,因此取幂是没有意义的,因此我怀疑这不会成为问题。)

This should do the same since c2 * c1^-x = c2 / (c1 ^ x) : 由于c2 * c1^-x = c2 / (c1 ^ x)因此应该这样做:

BigInteger elGamalDecrypt(BigInteger c1, BigInteger c2, BigInteger p, int x) {
    return c2.divide(c1.pow(x)).mod(p);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM