此代码属于我的安全作业。我正在尝试使用RSAEncrypt
函数对消息进行加密,并使用RSADecrypt
函数对字符进行解密。我的字母数组有26个元素。
例如:
RSAEncryption(lorem) -> Ciphertext = ?????
RSADecryption(?????) -> Plaintext = lorem
代码在这里:
static char alphabet[] = {'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'};
public static String RSAEncrypt() {
int[] keys;
String message, cipherText = "";
int p, q, n, x, e, d, index = 0;
System.out.println("Enter two prime integers: ");
p = sc.nextInt();
q = sc.nextInt();
n = p * q; //Modulus
x = (p - 1) * (q - 1); //φ(n)
if (n < 26) {
System.out.print("Please enter two prime numbers that their multiplication "
+ "is bigger than 26(Alphabet Lenght)!");
} else {
System.out.println("Enter a message to encrypt: ");
message = sc.next();
keys = RSAKeyGeneration(x);
e = keys[0]; //Public Key
d = keys[1]; //Private Key
for (int i = 0; i < message.length(); i++) {
char character = message.charAt(i);
for (int j = 0; j < alphabet.length; j++) {
if (character == alphabet[j]) {
index = j;
break;
}
}
double cipherTextDouble = (Math.pow(index, e) % n);
cipherText += alphabet[(int) cipherTextDouble % 26];
}
System.out.print("Original Message = " + message + ", Modulus = " + n + ", Public Key = " + e
+ ", Private Key = " + d + ", Ciphertext = ");
return cipherText;
}
return "";
}
public static String RSADecrypt() {
String cipherText, plainText = "";
int d, n;
System.out.println("Enter the encrypted message: ");
cipherText = sc.next();
System.out.println("Enter the private key(d and n(modulus)): ");
d = sc.nextInt();
n = sc.nextInt();
for (int i = 0; i < cipherText.length(); i++) {
for (int j = 0; j < 26; j++) {
if (cipherText.charAt(i) == alphabet[j]) {
int temp = 1;
for (int z = 0; z < d; z++) {
temp *= j;
temp = (temp % n);
}
plainText += alphabet[(temp % 26)];
}
}
}
return plainText;
}
public static int[] RSAKeyGeneration(int x) {
int[] keys = new int[2];
for (int i = x; i > 0; i--) {
if (i % x != 0 && x % i != 0) {
keys[0] = i; //Public Key
}
}
keys[1] = findInverse(keys[0], x); //Private Key
return keys;
}
问题是当我给出质数5和7时(模数= 35,Totient = 24,e = 5,d = 5)这给了我错误的明文。
RSAEncryption(abcdefghijklmnopqrstuvwxyz) -> Ciphertext = abghjkghiefqrnoplmxyuvwste
RSADecryption(abghjkghiefqrnoplmxyuvwste) -> Plaintext = abghefghijklmnopqrstuvwxyj
为什么'c','d','z'字符给我错误的输出。另外,当我给质数更大的时候,输出是完全错误的。我在哪里做错了?
最佳答案
RSA加密是幂模n
。您的n
是35,但是问题是您尝试使用此行将0到34范围内的密文转换为0到25范围内的密文:
cipherText += alphabet[(int) cipherTextDouble % 26];
这意味着〜25%(
(35-26)/35
)的密文字符将不正确。您需要将字母增加到35个条目并使用cipherText += alphabet[(int) cipherTextDouble];
同样,当您尝试增加质数时,您可能会很快遇到以双精度表示整数的精度问题。您将不得不切换到BigInteger类。
关于java - RSA加密和解密会产生一些错误的字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34047899/