今天给人家写了一个RSA代码,正好复习一下RSA,以前写的不知道到哪里去了。
import java.math.BigInteger;
import java.util.Random;
public class Main {
public static void main(String[] args) {
//待加密的明文信息
String pmsg="RSA信息";
//将明文信息转换成数字m,便于计算处理
BigInteger m = new BigInteger(pmsg.getBytes());
//构造一个随机生成器
Random rnd = new Random();
//生成两个50位的大素数p和q
BigInteger p = BigInteger.probablePrime(50,rnd);
BigInteger q = BigInteger.probablePrime(50,rnd);
//计算n
BigInteger n = p.multiply(q);
//计算fai(n)
BigInteger faiN= p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
//取得一个合适的d
BigInteger d = faiN.nextProbablePrime();
//计算e
BigInteger e = d.modInverse(faiN);
// 对信息加密
BigInteger c = m.modPow(e,n);
//将数字转化成可读明文
String msgm =new String(c.toByteArray());
System.out.println("加密信息:"+msgm);
//对信息进行解密
BigInteger jiemi = c.modPow(d,n);
//将数字转化成可读明文
String msg = new String(jiemi.toByteArray());
System.out.println("解密信息:"+msg);
}
}