分块解密,,,
import java.security.PrivateKey;
import java.security.Security;
import javax.crypto.Cipher;
import java.util.Base64;
public class RsaDecryptUtil {
public static String decrypt(String encryptedData, PrivateKey privateKey) throws Exception {// 添加BouncyCastle提供者支持Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());// 初始化解密器Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");cipher.init(Cipher.DECRYPT_MODE, privateKey);// 分块解密byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);ByteArrayOutputStream out = new ByteArrayOutputStream();int offset = 0;int maxDecryptBlock = 245;while (offset < encryptedBytes.length) {int length = Math.min(encryptedBytes.length - offset, maxDecryptBlock);byte[] decryptedBlock = cipher.doFinal(encryptedBytes, offset, length);out.write(decryptedBlock);offset += length;}// 返回解密结果return new String(out.toByteArray(), "UTF-8");
}// 加载私钥示例(假设私钥已加载为字符串)
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");return keyFactory.generatePrivate(keySpec);
}public static void main(String[] args) throws Exception {// 假设的私钥字符串String privateKeyStr = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQD...";PrivateKey privateKey = loadPrivateKey(privateKeyStr);// 待解密的密文String encryptedData = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...";// 解密String decryptedData = decrypt(encryptedData, privateKey);System.out.println("解密结果:" + decryptedData);
}
}