请用Java编写含有中文注释和输入输出的RSA算法
时间: 2024-03-13 10:47:29 浏览: 71
用Java实现RSA算法
以下是含有中文注释和输入输出的RSA算法的Java代码:
```java
import java.math.BigInteger;
import java.util.Scanner;
public class RSA {
// 生成密钥对
public static void genKeyPair() {
// 选择两个大素数p和q
BigInteger p = BigInteger.probablePrime(512, new java.util.Random());
BigInteger q = BigInteger.probablePrime(512, new java.util.Random());
// 计算n = p * q
BigInteger n = p.multiply(q);
// 计算φ(n) = (p-1) * (q-1)
BigInteger phiN = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
// 选择一个小于φ(n)的整数e
BigInteger e = BigInteger.valueOf(65537);
// 计算e关于φ(n)的模反元素d
BigInteger d = e.modInverse(phiN);
// 输出公钥和私钥
System.out.println("公钥: (" + n + ", " + e + ")");
System.out.println("私钥: (" + n + ", " + d + ")");
}
// 加密明文
public static BigInteger encrypt(BigInteger m, BigInteger n, BigInteger e) {
// 计算密文c = m^e mod n
BigInteger c = m.modPow(e, n);
return c;
}
// 解密密文
public static BigInteger decrypt(BigInteger c, BigInteger n, BigInteger d) {
// 计算明文m = c^d mod n
BigInteger m = c.modPow(d, n);
return m;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请选择操作:");
System.out.println("1. 生成密钥对");
System.out.println("2. 加密明文");
System.out.println("3. 解密密文");
int choice = scanner.nextInt();
switch (choice) {
case 1:
genKeyPair();
break;
case 2:
System.out.print("请输入明文m:");
BigInteger m = scanner.nextBigInteger();
System.out.print("请输入公钥n:");
BigInteger n = scanner.nextBigInteger();
System.out.print("请输入公钥e:");
BigInteger e = scanner.nextBigInteger();
BigInteger c = encrypt(m, n, e);
System.out.println("密文c = " + c);
break;
case 3:
System.out.print("请输入密文c:");
BigInteger c2 = scanner.nextBigInteger();
System.out.print("请输入私钥n:");
BigInteger n2 = scanner.nextBigInteger();
System.out.print("请输入私钥d:");
BigInteger d = scanner.nextBigInteger();
BigInteger m2 = decrypt(c2, n2, d);
System.out.println("明文m = " + m2);
break;
default:
System.out.println("输入错误!");
}
}
}
```
注意:这是一个简单的实现,实际使用中需要考虑更多的安全性问题。
阅读全文