【发布时间】:2019-08-16 19:10:39
【问题描述】:
我必须根据我对程序的要求使用p=78511和q=5657,代码执行没有错误,但我因为dec_key的值太大,它不显示解密的文本,继续运行。我该如何解决这个问题?有没有办法让 dec_key 更小,或者我做的解密方法都错了。在这里,我现在尝试在加密方法中传递一个字符“H”。 附上代码。 请不要阻止我的问题。我是新来的,不太确定如何提问,只是让我知道我错在哪里。谢谢!
package crypto.assgn4;
import static crypto.assgn4.Problem2.phi;
import java.math.BigInteger;
class Test {
static char[] characters = {' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
static BigInteger p = BigInteger.valueOf(78511);
static BigInteger q = BigInteger.valueOf(5657);
static BigInteger N = p.multiply(q);
static BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
static BigInteger e = BigInteger.ZERO, d;
public static void main(String args[]) {
e = new BigInteger("4");
while ((gcd(phi, e).intValue()>1)) {
e = e.add(new BigInteger("1"));
}
d = BigInteger.valueOf(mul_inverse(e, phi));
if (d.equals(e)) {
d.add(phi);
}
System.out.println("Encryption Key : "+e);
System.out.println("Decryption Key : "+d);
String c = encrypt("H",e,N);
String p = decrypt(c,d,N);
System.out.println("Cipher : "+c);
System.out.println("Text : " +p);
}
public static BigInteger gcd(BigInteger a, BigInteger b) {
while (b != BigInteger.ZERO) {
BigInteger temp = b;
b = a.mod(b);
a = temp;
}
return a;
}
public static int mul_inverse(BigInteger number, BigInteger sizeOfAlphabet) {
int a = number.intValue() % sizeOfAlphabet.intValue();
for (int x = 1; x < sizeOfAlphabet.intValue(); x++) {
if ((a * x) % sizeOfAlphabet.intValue() == 1) {
return getMod(x, sizeOfAlphabet.intValue());
}
}
return -1;
}
public static int getMod(int x, int y) {
int result = x % y;
if (result < 0) {
result += y;
}
return result;
}
/**
* ********************************************************************************
*/
static String encrypt(String plainText, BigInteger e, BigInteger N) {
StringBuilder cipherText = new StringBuilder();
for (int i = 0; i < plainText.length(); i++) {
int index = plainText.charAt(i);
cipherText.append("").append((char) (new BigInteger(index + "").pow(e.intValue()).mod(N).intValue()));
char c1 = (char) (new BigInteger(index + "").intValue());
}
return cipherText.toString();
}
static String decrypt(String cipherText, BigInteger d, BigInteger N) {
String plainText = "";
for (int i = 0; i < cipherText.length(); i++) {
int index = cipherText.charAt(i);
plainText += "" + (char) (new BigInteger(index + "").pow(d.intValue()).mod(N).intValue());
}
return plainText;
}
}
【问题讨论】:
-
你为什么要使用
.intValue()?除了使您的代码不那么正确和难以阅读之外,它对您没有任何作用。 -
(1) 您的
mul_inverse比必要的慢数百万倍;通常乘以 29 位数字也不适合 Javaint但你的 e 总是很小所以这可能不会命中 (2) 你不需要将int转换为十进制StringBigInteger的方法,只需使用BigInteger.valueOf(int)(3) 特别是对于 d,执行BigInteger.pow完成 thenmod比优化组合 @ 花费 much 更长的时间987654331@ (4) 对于提供任何安全性的 RSA 大小,您的代码将永远无法完成 (5) 请参阅回复char的评论
标签: java encryption rsa