import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class RSAChinese {
/**
* 创建密钥对生成器,指定加密和解密算法为RSA
* @param keylen
* @return
*/
public String[] createKey(int keylen) {// 输入密钥长度
String[] output = new String[5]; // 用来存储密钥的e n d p q
try {
KeyPairGenerator kpg = ("RSA");
(keylen); // 指定密钥的长度,初始化密钥对生成器
KeyPair kp = (); // 生成密钥对
RSAPublicKey puk = (RSAPublicKey) ();
RSAPrivateCrtKey prk = (RSAPrivateCrtKey) ();
BigInteger e = ();
BigInteger n = ();
BigInteger d = ();
BigInteger p = ();
BigInteger q = ();
output[0] = ();
output[1] = ();
output[2] = ();
output[3] = ();
output[4] = ();
} catch (NoSuchAlgorithmException ex) {
(()).log(, null, ex);
}
return output;
}
/**
* 加密在RSA公钥中包含有两个整数信息:e和n。对于明文数字m,计算密文的公式是m的e次方再与n求模。
* @param clearText 明文
* @param eStr 公钥
* @param nStr
* @return
*/
public String encrypt(String clearText, String eStr, String nStr) {
String secretText = new String();
try {
clearText = (clearText,"GBK");
byte text[]=("GBK");//将字符串转换成byte类型数组,实质是各个字符的二进制形式
BigInteger mm=new BigInteger(text);//二进制串转换为一个大整数
clearText = ();
BigInteger e = new BigInteger(eStr);
BigInteger n = new BigInteger(nStr);
byte[] ptext = ("UTF8"); // 获取明文的大整数
BigInteger m = new BigInteger(ptext);
BigInteger c = (e, n);
secretText = ();
} catch (UnsupportedEncodingException ex) {
(()).log(, null, ex);
}
return secretText;
}
/**
* 解密
* @param secretText 密文
* @param dStr 私钥
* @param nStr
* @return
*/
public String decrypt(String secretText, String dStr, String nStr) {
StringBuffer clearTextBuffer = new StringBuffer();
BigInteger d = new BigInteger(dStr);// 获取私钥的参数d,n
BigInteger n = new BigInteger(nStr);
BigInteger c = new BigInteger(secretText);
BigInteger m = (d, n);// 解密明文
byte[] mt = ();// 计算明文对应的字符串并输出
for (int i = 0; i < ; i++) {
((char) mt[i]);
}
String temp = ();//temp为明文的字符串形式
BigInteger b = new BigInteger(temp);//b为明文的BigInteger类型
byte[] mt1=();
try {
String clearText = (new String(mt1,"GBK"));
clearText=(clearText,"GBK");
return clearText;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
();
}
return null;
}
public static void main(String[] args) {
RSAChinese rsa = new RSAChinese();
String[] str = (1024);
String clearText = "123abc测试";
String secretText = (clearText, str[0], str[1]);
("明文是:" + clearText);
("密文是:" + secretText);
("解密后的明文是:" + (secretText, str[2], str[1]));
}
}