Java 实现 RSA 解密(算法模式为 RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING),代码如下。
package com.test.utils;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
@Slf4j
public class Test {
public static final String KEY_RSA_TYPE = "RSA";
public static final String ALGORITHM = "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING";
/**
* RSA 解密
*
* @param sourceBase64RSA base64 编码后的密文
* @param privateKeyBase64Str base64 编码后的私钥
* @return 明文
* @throws Exception 抛出异常
*/
public static String decode(String sourceBase64RSA, String privateKeyBase64Str) throws Exception {
Cipher oaepFromInit = Cipher.getInstance(ALGORITHM);
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1",
new MGF1ParameterSpec("SHA-1"), PSource.PSpecified.DEFAULT);
byte[] privateBytes = decryptBASE64(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 = decryptBASE64(sourceBase64RSA);
byte[] pt = oaepFromInit.doFinal(ct);
return new String(pt, StandardCharsets.UTF_8);
}
/**
* BASE64 解码,返回字节数组
*
* @param key 待解码的字符串
* @return 解码后的字节数组
*/
public static byte[] decryptBASE64(String key) {
return Base64.getDecoder().decode(key);
}
}