2013-03-15 67 views
-5

以下代碼基於密碼學。 在我的構造函數,我初始化這樣的:解密IllegalBlockSizeException

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();} 

我有這樣的代碼被稱爲加密和實際工作

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) 

那麼請任何人都可以解釋爲什麼我得到這個異常?

+0

可能是這個鏈接可以幫助你.. [JCE加密 - 數據加密標準(DES)教程](http://www.mkyong.com/java/jce-encryption-data-encryption-standard-des-tutorial /) – Smit 2013-03-15 16:24:19

回答

0

你可能會得到這個例外,因爲txtEncryptOutput.getText().getBytes()長度不是8

多你可以通過調試器下檢查,或輸出長度與終端的日誌系統證實了這一點。

2

您無法將隨機字節序列解碼到String。大多數字符編碼不會將每個字節或字節序列映射到一個字符;這些將用&#xFFFD替換信息; (替換字符)。

取而代之的是,將密文轉換爲可打印的字符串,然後使用適當的編碼(如Base-64)再返回。

+0

請參閱[本答案](http://stackoverflow.com/a/6077568/3474)以獲取更多解釋。 – erickson 2013-03-15 17:19:35