以下代码基于密码学。在我的构造函数中,我初始化了这个:
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();}
但是下面的 Decrypt 按钮下的代码不起作用
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)
所以请谁能解释我为什么会收到这个异常?