You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Java RSA解密时的IllegalBlockSizeException异常?

RSA解密IllegalBlockSizeException问题修复

你的代码存在两个关键错误,直接导致了解密时的异常:

  1. 解密前未做Base64解码:加密后返回的是Base64编码的字符串,你直接调用message.getBytes()会把Base64字符串本身转成字节数组,而非加密生成的原始字节数据。Base64编码后的字节长度远超过RSA密钥对应的块大小(比如1024位密钥对应最大128字节的加密数据),因此触发IllegalBlockSizeException。

  2. 解密结果错误编码:解密后的字节数组是原始明文的字节,应该直接转成字符串,而非再次用Base64编码,否则得到的不是原明文内容。

修正后的解密方法代码:

private static String decryptString(PrivateKey privateKey, String message) throws Exception {
    Cipher decrypt = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    decrypt.init(Cipher.DECRYPT_MODE, privateKey);
    // 先Base64解码得到原始加密字节数组
    byte[] encryptedBytes = Base64.getDecoder().decode(message);
    byte[] decrypted = decrypt.doFinal(encryptedBytes);
    // 直接将解密后的字节转成字符串(显式指定字符集避免环境差异)
    return new String(decrypted, StandardCharsets.UTF_8);
}

同时建议加密时也显式指定字符集,避免不同环境下默认字符集不一致导致的问题:

private static String encryptString(PublicKey publicKey, String message) throws Exception {
    Cipher encrypt = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    encrypt.init(Cipher.ENCRYPT_MODE, publicKey);
    // 显式指定UTF-8字符集
    byte[] encrypted = encrypt.doFinal(message.getBytes(StandardCharsets.UTF_8));
    return Base64.getEncoder().encodeToString(encrypted);
}

内容的提问来源于stack exchange,提问作者ed-ict

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:45:50