Java RSA加解密算法转Ruby

狼王_ 2017-07-17 11:02:09
如何将下列的 Java RSA加解密算法转换为Ruby啊?

/**
* 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 "";

}
...全文
395 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
狼王_ 2017-07-17
  • 打赏
  • 举报
回复
/**
	 * @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());

	}

2,763

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ruby/Rails
社区管理员
  • Ruby/Rails社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧