在我的学校,老师们被告知必须编写一个程序,用RSA加密来加密一个数字。整个程序运行良好,除了一小部分,有时在执行时冻结程序。 下面是该类的代码:
package newpackage;
import java.lang.Math.*;
import java.util.*;
import java.lang.*;
import java.io.*;
public class CrittografiaRSA {
public static Random rand = new Random();
public static double d;
public static String cod;
public static int e;
public static boolean EuclideAlgorithm(int a, int b) {
int r;
boolean k = false;
while (b != 0) {
r = a % b;
a = b;
b = r;
}
if (a == 1) {
k = true;
}
if (a != 1) {
k = false;
}
return k;
}
public static String RSA(int p, int q, String mex, int e) {
CrittografiaRSA.cod = "";
int pqless, n, i = 0, v;
boolean GCD = false, dVerify = false, PQPN;
PQPN = EuclideAlgorithm(p, q);
if (PQPN == false) {
cod = "P e Q non sono primi fra loro";
return cod;
}
n = p * q;
pqless = (q - 1) * (p - 1);
if (NewJFrame.generateE == true) {
while (GCD == false || e >= pqless || e == 1) {
e = rand.nextInt(pqless);
System.out.println(e);
GCD = EuclideAlgorithm(e, pqless);
}
}
if (NewJFrame.generateE == false) {
GCD = EuclideAlgorithm(e, pqless);
if (GCD == false || e >= pqless || e == 1) {
cod = "La E fornita non è adatta.";
return cod;
}
}
CrittografiaRSA.d = e;
while (e == CrittografiaRSA.d || d == 0) {
while (dVerify == false) {
CrittografiaRSA.d = ((i * pqless) + 1) / (double) e;
v = (int) d;
if (d == v) {
dVerify = true;
}
i = i + 1;
}
if (e == i && NewJFrame.generateE == false) {
cod = "Nessuna chiave D generabile con le chiavi inserite";
return cod;
}
}
System.out.println("La chiave pubblica è: (" + n + "," + e + ")n" + "La chiave privata è: (" + n + "," + (int) d + ")");
if (NewJFrame.cryptoChar == false) {
int mexx = Integer.parseInt(mex);
if (n <= mexx) {
cod = "Messaggio troppo grande per le chiavi fornite";
return cod;
}
long c;
double pot = Math.pow(mexx, e);
c = (long) (pot % n);
CrittografiaRSA.cod = Long.toString(c);
}
return CrittografiaRSA.cod;
}
}
特别是,程序就在这里冻结:
if(NewJFrame.generateE==true){
while(GCD == false || e>=pqless || e==1){
e = rand.nextInt(pqless);
System.out.println(e);
GCD = EuclideAlgorithm(e, pqless);
}
}
然而,我注意到,p 和 q 越小,出错的机会就越高。
希望代码是可以理解的,我删除了意大利语注释'因为 IDK 如果整个代码真的是必要的,但无论如何。 谢谢你帮助我。
while(b != 0)
{
r = a % b;
a = b;
b = r;
System.out.println(b); // add this
}
此修改后应用程序是否仍然冻结?
如果p
或q
等于1
则e
将始终等于pqless
,因为rand.nextInt(pqless)
生成一个介于0
和pqless
之间的随机数。对于p
和/或q
的值为1
,pqless = 0
如此e = 0
。因此,无限循环开始了。
pqless = (q - 1) * (p - 1);
if (NewJFrame.generateE == true) {
while (GCD == false || e >= pqless || e == 1) {
e = rand.nextInt(pqless);
System.out.println(e);
GCD = EuclideAlgorithm(e, pqless);
}
}