【问题标题】:Decrypting IllegalBlockSizeException解密 IllegalBlockSizeException
【发布时间】:2013-03-15 16:14:22
【问题描述】:

以下代码基于密码学。 在我的构造函数中,我初始化了这个:

try{
        //To generate the secret key
        KeyGenerator keyGen = KeyGenerator.getInstance("DES");
        sKey = keyGen.generateKey();
        //Initialize the cipher instance to use DES algorithm, ECB mode,
        //and PKCS#5 padding scheme.
        cipherObj = Cipher.getInstance("DES/ECB/PKCS5Padding");
    }
    catch(NoSuchAlgorithmException nsae){nsae.printStackTrace();

    }
    catch(NoSuchPaddingException nspe){nspe.printStackTrace();}

我在一个名为 Encrypt 的按钮下有这段代码,它实际上在工作

try{
    //Initialize the cipher with secret key to encrypt the data.
    cipherObj.init(Cipher.ENCRYPT_MODE, sKey);
    //Read the data into byte array
    byte[] textToEncrypt = txtTobeEncrypted.getText().getBytes();
    //To encrypt the data
    byte[] encryptedData = cipherObj.doFinal(textToEncrypt);
    //Display the encrypted data
    String encryptedText = new String(encryptedData);
    txtEncryptOutput.setText(encryptedText);
}
catch(InvalidKeyException ivkey){ivkey.printStackTrace();}
catch(BadPaddingException bpe){bpe.printStackTrace();}
catch(IllegalBlockSizeException ilbs){ilbs.printStackTrace();}

但解密按钮下的以下代码不起作用

try{
    //Initialize the cipher with secret key to encrypt the data.
    cipherObj.init(Cipher.DECRYPT_MODE, sKey);
    //Read the data into byte array
    byte[] textToDecrypt = txtEncryptOutput.getText().getBytes();
    //To decrypt the data
    byte[] plainData = cipherObj.doFinal(textToDecrypt);
    //Display the encrypted data
    String thePlainText = new String(plainData);
    txtDecrypt.setText(thePlainText);
}
catch(InvalidKeyException ivkey){ivkey.printStackTrace();}
catch(BadPaddingException bpe){bpe.printStackTrace();}
catch(IllegalBlockSizeException ilbs){ilbs.printStackTrace();}

得到的异常如下:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:750)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314)
at javax.crypto.Cipher.doFinal(Cipher.java:2086)
at cryptography.FileEncryption.cmdDecryptActionPerformed(FileEncryption.java:209)

那么请谁能解释一下为什么我会收到这个异常?

【问题讨论】:

标签: java encryption


【解决方案1】:

您无法将随机字节序列解码为String。大多数字符编码不会将每个字节或字节序列映射到一个字符。这些将用 �(替换字符)替换信息。

相反,将密文转换为可打印的字符串,然后使用合适的编码(如 Base-64)再次返回。

【讨论】:

    【解决方案2】:

    您可能会遇到此异常,因为 txtEncryptOutput.getText().getBytes() 的长度不是 8 的倍数。

    您可以通过在调试器下检查它来确认这一点,或者将长度输出到您的日志系统的终端。

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多