JAVA使用RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING加密解密
作者:互联网
项目中用户登陆密码需要前端RSA加密,后端RSA解密。项目验收前的安全审查说有高危漏洞,RSA使用的模式不够安全啥的。
之前使用的RSA模式RSA/ECB/PKCS1Padding,RSA/ECB/OAEPWithMD5AndMGF1Padding都报高危,只能使用RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING
网上现成的例子好像没有,连在线加密解密rsa的网站都没用这个模式。外网找到个有这个模式的在线加密解密网站Online RSA Encryption, Decryption And Key Generator Tool
其中The generated private key is generated in PKCS#8 format and the generated public key is generated in X.509 format.这句话还解答了我疑惑。因为从String类型的私钥公钥,转换成对象类型的,用到了PKCS8EncodedKeySpec和X509EncodedKeySpec。单独的一个加密/解密接口,入参是String,后续要转成对象。
贴一个解密的简单java接口代码,sourceBase64RSA加密后的密码,privateKeyBase64Str私钥
public static String decode(String sourceBase64RSA,String privateKeyBase64Str) throws Exception{
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING"); OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-1"), PSource.PSpecified.DEFAULT); byte[] privateBytes = Base64.decodeBase64(privateKeyBase64Str); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA_TYPE); PrivateKey privkey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); oaepFromInit.init(Cipher.DECRYPT_MODE, privkey, oaepParams); byte[] ct = Base64.decodeBase64(sourceBase64RSA); byte[] pt = oaepFromInit.doFinal(ct); System.out.println(new String(pt, StandardCharsets.UTF_8)); return new String(pt, StandardCharsets.UTF_8);
}
标签:JAVA,String,OAEPWITHSHA,解密,RSA,ECB,new,加密,256ANDMGF1PADDING 来源: https://blog.csdn.net/daggerin7/article/details/121999324