Ello!我正在開發一個聊天應用程序,通過AES/CBC/PKCS5 Padding加密它的數據。它通過客戶端將加密消息發送到服務器進行發送和解密。不幸的是,每當我解密消息時,我得到的錯誤如下:javax.crypto.IllegalBlockSizeException:使用填充密碼解密時,輸入長度必須是16的倍數。加密是基於這個程序:(http://www.scottjjohnson.com/blog/AesWithCbcExample.java),它工作得很好,我看不出我的代碼和那個之間的區別,除了我必須從字符串轉換爲字節數組。這裏是我的代碼代碼:無法修復「錯誤:使用密碼密碼解密時,輸入長度必須是16的倍數」
客戶端(加密):
String message = textField.getText();
// generate a key
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128); // To use 256 bit keys, you need the "unlimited strength" encryption policy files from Sun.
byte[] key = keygen.generateKey().getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
// build the initialization vector. This example is all zeros, but it
// could be any value or generated using a random number generator.
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
// initialize the cipher for encrypt mode
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
// encrypt the message
byte[] encrypted = cipher.doFinal(message.getBytes());
System.out.println("Ciphertext: " + encrypted + "\n");
System.out.println(encrypted);
out.println(encrypted);
textField.setText("");
服務器端:
String input = in.readLine();
writer.println("MESSAGE " + input);
客戶端(解密):
//DECRYPTION
System.out.println(line);
line = line.substring(8);
System.out.println(line);
// generate a key
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128); // To use 256 bit keys, you need the "unlimited strength" encryption policy files from Sun.
byte[] key = keygen.generateKey().getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
// build the initialization vector. This example is all zeros, but it
// could be any value or generated using a random number generator.
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
// reinitialize the cipher for decryption
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
// decrypt the message
byte[] decrypted = cipher.doFinal(line.getBytes());
System.out.println("Plaintext: " + new String(decrypted) + "\n");
messageArea.append(name + ": " + decrypted + "\n");
messageArea.setCaretPosition(messageArea.getDocument().getLength());
也有很多類似的問題,請做一個小的搜索。 – Henry
哈哈我一直在研究上週所有這些問題。我的問題不是錯誤本身,而是我如何繼續接收它,即使我的輸入是16的倍數。 – Silver