代码改变世界

rsa 加密后 Java使用 私钥解密


A:建议使用openssl 来生成rsa pkcs1 2048格式的公私钥。例如可使用:openssl genrsa -out private.pem 2048 来生成私钥,并使用openssl rsa -in private.pem -pubout -out public.pem从私钥来产生公钥。


pkcs8 -topk8 -inform PEM -outform PEM -in private.pem -out privateFormate.pem -nocrypt

 

替换privateFormate.pem换行得到 Java使用的私钥字符串


public static String decrypt(String str, String privateKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);

RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}

posted on 2022-01-20 11:00  Captain林  阅读(600)  评论(0编辑  收藏  举报

导航