2,763
社区成员
发帖
与我相关
我的任务
分享
/**
* RSA公钥加密明文
*
* @param content
* 待加密明文
* @return 密文
*/
public static String publicEnc(String content, String pk) {
try {
KeyFactory keyf = KeyFactory.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
PublicKey pubkey = null;
InputStream is = new ByteArrayInputStream(pk.getBytes("utf-8"));
byte[] pubbytes = new byte[new Long(pk.length()).intValue()];
is.read(pubbytes);
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decode(new String(pubbytes)));
pubkey = keyf.generatePublic(pubX509);
cipher.init(Cipher.ENCRYPT_MODE, pubkey);
byte[] cipherText = cipher.doFinal(content.getBytes());
// 转换为Base64编码存储,以便于internet传送
return Base64.encode(cipherText);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* RSA私钥解密密文
*
* @param content
* 待解密密文
* @return 明文
*/
public static String privateDec(String content, String prikeyStr) {
try {
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey privkey = null;
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
InputStream key = new ByteArrayInputStream(prikeyStr.getBytes("utf-8"));
byte[] pribytes = new byte[new Long(prikeyStr.length()).intValue()];
key.read(pribytes);
// 生成私钥
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(new String(pribytes)));
privkey = keyf.generatePrivate(priPKCS8);
cipher.init(Cipher.DECRYPT_MODE, privkey);
byte[] newPlainText = cipher.doFinal(Base64.decode(content));
return (new String(newPlainText));
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* @param path
* 文件路径
* @throws Exception
*
* 生成rsa 公私钥,加密base64编码存储到文件系统
*/
public static void createKeyPairs(String path) throws Exception {
// create the keys
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024, new SecureRandom());
KeyPair pair = generator.generateKeyPair();
PublicKey pubKey = pair.getPublic();
PrivateKey privKey = pair.getPrivate();
byte[] pk = pubKey.getEncoded();
byte[] privk = privKey.getEncoded();
// base64编码,屏蔽特殊字符
String strpk = new String(Base64.encode(pk));
String strprivk = new String(Base64.encode(privk));
// 输出私钥文件
File priKeyfile = new File(path + "rsa_pri_key.pem");
FileOutputStream out = new FileOutputStream(priKeyfile);
out.write(strprivk.getBytes());
// 输出公钥文件
File pubKeyfile = new File(path + "rsa_pub_key.pem");
FileOutputStream outPub = new FileOutputStream(pubKeyfile);
outPub.write(strpk.getBytes());
}