2013-08-20 110 views
0

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()); 
+0

也有很多類似的問題,請做一個小的搜索。 – Henry

+0

哈哈我一直在研究上週所有這些問題。我的問題不是錯誤本身,而是我如何繼續接收它,即使我的輸入是16的倍數。 – Silver

回答

4

您的問題無關與密碼學。您無法在您的客戶端和服務器之間正確傳輸數據。

我相當肯定out.println(encrypted)你想要做的,雖然我不完全清楚,因爲我不知道out類型是什麼。您也不應該在解密代碼中調用line.getBytes()

您應該將您的密文轉換爲非有損字符串形式,如十六進制或base64。因此,嘗試:

out.println(DatatypeConverter.printHexBinary(encrypted)); 

byte[] decrypted = cipher.doFinal(DatatypeConverter.parseHexBinary(line)); 
+0

嗯,它不會再給出舊錯誤,但現在我收到了這個新錯誤:javax.crypto.BadPaddingException :給定的最終塊未正確填充。 – Silver

+0

關於如何解決它的任何想法? – Silver

相關問題