日期:2014-05-20 浏览次数:20839 次
package com.bxuanzhao.key;
import java.math.*;
import java.util.Random;
import java.util.Scanner;
public class RsaFactory {
public BigInteger publicKeyN, publicKeyE; //公钥
private BigInteger privateKey; //私钥
BigInteger p, q;
public RsaFactory(BigInteger p, BigInteger q) {
this.p = p;
this.q = q;
publicKeyN = p.multiply(q);
this.publicKeyE = getPublicKeyE();
this.privateKey = getPrivateKey();
System.out.println("公钥E: " + publicKeyE);
System.out.println("公钥N: " + publicKeyN);
System.out.println("私钥: " + privateKey);
}
public BigInteger getPublicKeyE () {
Random rand = new Random();
publicKeyE = BigInteger.probablePrime(40,rand);
return publicKeyE;
}
public BigInteger getPrivateKey () {
BigInteger fn = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
privateKey = publicKeyE.modInverse(fn);
return privateKey;
}
public BigInteger Encryption(BigInteger msg) {
BigInteger cipher = msg.modPow(publicKeyE, publicKeyN);
//System.out.println("密文: "+ cipher);
return cipher;
}
public BigInteger decryp(BigInteger cipher) {
BigInteger msg = cipher.modPow(privateKey, publicKeyN);
//System.out.println("明文:" + msg);
return msg;
}
public void rsa(String msg) {
int m;
String s;
char[] msgArr = msg.toCharArray();
int length = msgArr.length;
String[] cipherStr = new String[length];
BigInteger cipher[] = new BigInteger[length];
BigInteger text[] = new BigInteger[length];
for(int i=0; i<length; i++) { //加密成cipherStr
m = (int)msgArr[i];
s = String.valueOf(m);
text[i] = new BigInteger(s);
cipher[i] = this.Encryption(text[i]);
cipherStr[i] = cipher[i].toString(16); //加密后的密文
}
char[] clearMsg = new char[length];
for(int i=0; i<length; i++) { //解密
text[i] = new BigInteger(cipherStr[i],16);
m = this.decryp(text[i]).intValue();
clearMsg[i] = (char)m; //解密后的明文
}
System.out.println("加密后的密文为:");
for(int i=0; i<length; i++)
System.out.print(cipherStr[i]);
System.out.println("\n"+"解密后的密文为:");
for(int i=0; i<length; i++)
System.out.print(clearMsg[i]);
}
public static void main(String[] arg) {
Random rand = new Random();
BigInteger p = BigInteger.probablePrime(20,rand);
BigInteger q = BigInteger.probablePrime(20,rand);
RsaFactory rsa = new RsaFactory(p, q);
String mesg;
System.out.println("输入要加密的消息:");
Scanner sc = new Scanner(System.in);
mesg = sc.nextLine();
if(mesg != null)
rsa.rsa(mesg);
else
System.out.println("没有需要加密的消息");
}
}