import java.io.PrintWriter; import java.math.BigInteger; import java.util.Scanner; /** * RSA算法 */ public class RSA { private static final BigInteger a = BigInteger.valueOf('a'); private static final Scanner sc = new Scanner(System.in); private static final PrintWriter print = new PrintWriter(System.out,true); // 公钥 public static BigInteger n; public static BigInteger e; // 私钥 public static BigInteger d; // 帮助信息 private static final String help = "1. 生成密钥 2. RSA加密 3. RSA解密 4.重置数据 5.输入密钥 -1. 退出"; public static void main(String[] args) { while (true) { print.println("当前数据" + (n == null ? "" : " n = "+n) + (e == null ? "" : " e = "+e) + (d == null ? "" : " d = "+d)); print.println(help); int i = sc.nextInt(); switch (i) { case 1 -> createN(); case 2 -> getCipher(); case 3 -> getPlain(); case 4 -> init(); case 5 -> { print.println("请输入密钥 n,e,d"); n = sc.nextBigInteger(); e = sc.nextBigInteger(); d = sc.nextBigInteger(); } case -1 -> System.exit(0); } } } private static void init() { n = null; e = null; d = null; } private static void getPlain() { if (d == null) { print.println("请输入密钥"); d = sc.nextBigInteger(); } print.println("请输入密文"); getModPow(d); } private static void getModPow(BigInteger d) { sc.next().chars().mapToObj(c -> BigInteger.valueOf(c - 'a')).forEach(i -> { BigInteger j = i.modPow(d, n); j = j.add(a); print.print((char) j.intValue()); }); print.println(); } private static void createN() { print.println("请输入两个质数p,q"); BigInteger p = sc.nextBigInteger(); BigInteger q = sc.nextBigInteger(); n = p.multiply(q); BigInteger f = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)); e = BigInteger.TWO; while (!f.gcd(e).equals(BigInteger.ONE)) { e = e.add(BigInteger.ONE); } d = e.modInverse(f); print.println("公钥: (" + n + "," + e + ")"); print.println("私钥: (" + n + "," + d + ")"); } private static void getCipher() { if (n == null || e == null) { print.println("请输入公钥n,e"); n = sc.nextBigInteger(); e = sc.nextBigInteger(); } print.println("请输入明文"); getModPow(e); } }