RSA解密时报错 Data must not be longer than 128 bytes

RSA解密时报错 Data must not be longer than 128 bytes

最近RSA解密是遇到一个问题,就是报错 Data must not be longer than 128 bytes。
笔者是java代码,报错是在 cipher.doFinal(data) 这句产生的。

研究多个文档后发现最终解决办法,因为公钥私钥不是我生成的,所以无法更换,只能分块解密。
在网上看到如果时无填充,就用私钥的byte长度 / 8, 如果是有填充加密,则再 -11。这些方法我试了。都没有用。最后发现一个有用的,就是直接用128来分块。这个应该是跟加密方如何加密的有关系。

直接上代码

private final static int MAX_DECRYPT_BLOCK = 128;	

private static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        // 返回UTF-8编码的解密信息
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        String s = new String(decryptedData, "UTF-8");
        System.out.println(s);
        return null;
    }

再放一段同类型加密

private static final int MAX_ENCRYPT_BLOCK = 127;
public static String encrypt(String data, PublicKey publicKey) throws Exception {
          Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
          cipher.init(Cipher.ENCRYPT_MODE, publicKey);
          int inputLen = data.getBytes().length;
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          int i = 0;
          int offset = 0;
          byte[] cache;
          // 对数据分段加密
          while (inputLen - offset > 0) {
              if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                  cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
              } else {
                  cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
              }
              out.write(cache, 0, cache.length);
              i++;
              offset = i * MAX_ENCRYPT_BLOCK;
          }
          byte[] encryptedData = out.toByteArray();
          out.close();
          // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
          return new String(Base64.encodeBase64String(encryptedData));
      }

如果有用希望大家能点个赞!也欢迎评论区一起交流。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值