2013-08-20 81 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

相关问题