最近工作上用到了这个填充模式的加解密,网上例子也很少,记录一下吧。
加密:
public static String encrypt( String data) throws Exception {
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA1", "MGF1", new MGF1ParameterSpec("SHA-1"), PSource.PSpecified.DEFAULT);
byte[] publicBytes = Base64.decodeBase64(publick_key);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
oaepFromInit.init(Cipher.ENCRYPT_MODE, publicKey, oaepParams);
byte[] bytes = oaepFromInit.doFinal( data.getBytes("UTF-8"));
return Base64.encodeBase64String(bytes);
}
解密:
public static String decode(String sourceBase64RSA) throws Exception{
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA1", "MGF1", new MGF1ParameterSpec("SHA-1"), PSource.PSpecified.DEFAULT);
byte[] privateBytes = Base64.decodeBase64(private_key);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privkey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
oaepFromInit.init(Cipher.DECRYPT_MODE, privkey, oaepParams);
byte[] ct = Base64.decodeBase64(sourceBase64RSA);
byte[] pt = oaepFromInit.doFinal(ct);
return new String(pt, StandardCharsets.UTF_8);
}
每次加密的结果不一样,和填充模式有关系,详细可以网上查阅下原因。
可以用这个网站校验一下加解密:
Online RSA Encryption, Decryption And Key Generator Tool (javainuse.com)