javax.crypto.IllegalBlockSizeException [英] javax.crypto.IllegalBlockSizeException

查看:665
本文介绍了javax.crypto.IllegalBlockSizeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在解密从servlet获得的数据时遇到麻烦.

我的代码是

Hi,

I''m in trouble to decrypt the data which I got from servlet.

MY code is

//getting the content from servlet
 URL url = new URL("http://localhost:8084/DataService/GetData?ChartName=preferences");
        //open url connection
        URLConnection yc = url.openConnection();
        //get value in stream format
        InputStream inputStream = yc.getInputStream();
        byte[] data = new byte[2125];
        inputStream.read(data);
        inputStream.close();


  // get the key
  DESKeySpec spec = new DESKeySpec(keyBytes);
        SecretKeyFactory instance = SecretKeyFactory.getInstance("DES");
        SecretKey key = instance.generateSecret(spec);
        
     //decrypction
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] doFinal = cipher.doFinal(data);
        System.out.println(new String(doFinal));


我收到以下错误


and I''m getting the following error

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..)
        at javax.crypto.Cipher.doFinal(DashoA13*..)
        at cbcdemo.Main.main(Main.java:86)


在此先感谢


thanks in advance

推荐答案

错误消息说明了一切:
The error message says it all:
Input length must be multiple of 8 when decrypting with padded cipher


您将为其提供2125字节,这不是8的倍数.

加密时,使用填充来使您的输入达到块大小的倍数(因此最后一个输入块为完整大小).解密时,需要解密完整的块,然后剥离或忽略解密输出中的任何填充.有很多技术可以识别什么是真实"数据以及什么是填充.

关键是使用DES/ECB,加密数据以8字节为一组.纯文本可以是任意长度,并且通过加密时的填充可以弥补任何差异.如果您对某些内容进行加密,然后丢弃最后一块的一部分,那么解密时就永远不会恢复到最后一块.因此,您需要从servlet读取8字节的倍数.

如果您喜欢答案,请投票并接受.

彼得


You are providing it with 2125 bytes, which is not a multiple of 8.

When you are ENcrypting, padding is used to make your input up to a multiple of the block size (so the last input block is full size). When you are DEcrypting, you need to decrypt full blocks, then strip off or ignore any padding in the decrypted output. There are a number of techniques for identifying what is "real" data and what is padding.

The whole point is that using DES/ECB, encrypted data comes in blocks of 8 bytes. Plain text can be any length, and any difference is made up by padding during encryption. If you encrypt something, then throw away part of the last block, you''ll never recover the last block when you decrypt. So, you''ll need to read a multiple of 8 bytes from your servlet.

If you like the answer, vote and accept it.

Peter


这篇关于javax.crypto.IllegalBlockSizeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆