Java RSA算法的实现
我的任务是实现RSA算法,我在Cormen的书中读到了它,并从那里获得了大部分信息。在我面对大的Java RSA算法的实现,java,algorithm,math,encryption,cryptography,Java,Algorithm,Math,Encryption,Cryptography,我的任务是实现RSA算法,我在Cormen的书中读到了它,并从那里获得了大部分信息。在我面对大的p和q素数之前,我一直认为它很有效。对于250或更低的数字,加密和解密效果很好,但是如果它们更大,模指数返回负数,这是没有意义的 我知道加密的数字不能大于n。我读到,我也可以使用扩展GCD算法计算逆模,并将x作为该值,但当我尝试调用extendededuclid(phi,e)[1]时,它返回的值与RSA类中的函数不同。我怎样才能修好它 下面是计算键所需的所有组件的代码 欧几里德算法 您面临的问题是整数
p
和q
素数之前,我一直认为它很有效。对于250或更低的数字,加密和解密效果很好,但是如果它们更大,模指数返回负数,这是没有意义的
我知道加密的数字不能大于n
。我读到,我也可以使用扩展GCD算法计算逆模,并将x
作为该值,但当我尝试调用extendededuclid(phi,e)[1]
时,它返回的值与RSA类中的函数不同。我怎样才能修好它
下面是计算键所需的所有组件的代码
欧几里德算法
您面临的问题是整数溢出,因此如果您试图在有符号整数中存储大于2^31-1的数字,这是不可能的。因此,当你达到这个极限时,结果是这个数字变成了-2^31-1 您要做的是研究BigInteger类,它将允许您存储更大的数字,并且应该可以正常工作 整数溢出发生在ModularExponentiation类的此行:
d = (d * a) % n;
对于给定的一对整数(a,b),存在无穷多对整数(x,y),因此ax+by=gcd(a,b)。extendedEuclid给出了一个这样的对。+1,但它是否应该包装为
-2^31
,而不是-2^31-1
?
public class Modular {
public static int modularExponentation(int a, int b, int n) {
int c = 0;
int d = 1;
String binaryString = Integer.toBinaryString(b);
for (int i = 0; i < binaryString.length(); i++) {
c = 2 * c;
d = (d * d) % n;
if (binaryString.charAt(i) == '1') {
c = c + 1;
d = (d * a) % n;
}
}
return d;
}
}
public class RsaKeyGenerator {
int d;
int e;
int n;
public RsaKeyGenerator() {
int p = 827;
int q = 907;
n = p * q;
int phi = (p - 1) * (q - 1);
e = computeCoPrime(phi);
d = invMod(e, phi);
System.out.println("Public: " + e);
System.out.println("Private: " + d);
}
private static int computeCoPrime(int phi) {
int e = 2;
while (Euclid.euclid(e, phi) != 1) {
e++;
}
return e;
}
private int invMod(int a, int n) {
int a0, n0, p0, p1, q, r, t;
p0 = 0;
p1 = 1;
a0 = a;
n0 = n;
q = n0 / a0;
r = n0 % a0;
while (r > 0) {
t = p0 - q * p1;
if (t >= 0) {
t = t % n;
} else {
t = n - ((-t) % n);
}
p0 = p1;
p1 = t;
n0 = a0;
a0 = r;
q = n0 / a0;
r = n0 % a0;
}
return p1;
}
public int encrypt(int num) {
return Modular.modularExponentation(num, e, n);
}
public int decrypt(int cipher) {
return Modular.modularExponentation(cipher, d, n);
}
public static void main(String[] args) {
RsaKeyGenerator rsa = new RsaKeyGenerator();
int cip = rsa.encrypt(1343);
System.out.println(cip);
System.out.println(rsa.decrypt(cip));
}
}
d = (d * a) % n;