【发布时间】:2019-07-22 19:15:07
【问题描述】:
我有一个使用 RSA 算法加密和解密数字的简单 java 代码
如果有人可以帮助我让这段代码从用户那里读取一个文本(字符串)并解密它而不只是数字,而是以一种简单的方式,这样我就可以在之后为代码绘制流程图:)
https://codedost.com/css/java-program-rsa-algorithm/
import java.util.*;
import java.math.*;
public class RSA {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int p, q, n, z, d = 0, e, i;
System.out.println("Enter the number to be encrypted and decrypted");
int msg = sc.nextInt();
double c;
BigInteger msgback;
System.out.println("Enter 1st prime number p");
p = sc.nextInt();
System.out.println("Enter 2nd prime number q");
q = sc.nextInt();
n = p * q;
z = (p - 1) * (q - 1);
System.out.println("the value of z = " + z);
for (e = 2; e < z; e++) {
if (gcd(e, z) == 1) // e is for public key exponent
{
break;
}
}
//e should be in the range 1-z
System.out.println("the value of e = " + e);
// calculate d
for (i = 0; i <= 9; i++) {
int x = 1 + (i * z);
if (x % e == 0) //d is for private key exponent
{
d = x / e;
break;
}
}
System.out.println("the value of d = " + d);
c = (Math.pow(msg, e)) % n;
//Encryptin C = msg ^e mod n
System.out.println("Encrypted message is : -");
System.out.println(c);
//converting int value of n to BigInteger
BigInteger N = BigInteger.valueOf(n);
//converting float value of c to BigInteger
BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
//Decrypt , P = Cˆd mod N , msgback = P
System.out.println("Derypted message is : -");
System.out.println(msgback);
}
static int gcd(int e, int z) {
if (e == 0) {
return z;
} else {
return gcd(z % e, e);
}
}
}
【问题讨论】:
-
RSA 仅适用于数字;但是您可以,例如将您的字符串转换为字节,并单独加密每个字节;或将 8 个字节组合成一个 long 并加密 long-s;或使用其他技术(例如将先前计算的值添加到被加密的下一个字符等)。
-
通常你会对字节进行操作并使用
BigInteger来计算。 -
(1) 最大 31 位 p 和 q,更不用说最大 31 位 n,太小而无法提供任何安全性 (2) 计算 d 的方法无法使用非荒谬的 n 甚至远低于 31 位 (3) 使用 Math.pow 对超过 52 位不起作用,并且为合理的大小执行 pow then mod (not combined) 将需要更长的时间比地球存在 (4) 即使有合理的大小和工作代码,未填充的 RSA 大多不安全;这对于 SO 来说是 OT,但在加密和安全堆栈上被数十个 Q 所涵盖(5)这些基本错误可以通过阅读维基百科来避免
-
为避免大文本的 CPU 成本过高,您可以有一个标头来表示通过公钥加密交付的主密钥,然后使用来自该主密钥的 AES 文件的其余部分。
-
@Daniele 我知道,但不幸的是我没有那种编程技能:(
标签: java string security encryption rsa