当前位置: 首页 > 知识库问答 >
问题:

无法修复“错误:使用pad密码解密时输入长度必须是16的倍数”

冯澄邈
2023-03-14
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());

共有1个答案

关项明
2023-03-14

你的问题与密码学无关。您无法在客户端和服务器之间正确传输数据。

我很肯定out.println(encrypted)不是您想要做的,尽管我不是很清楚,因为我不知道out的类型。也不应该在解密代码中调用line.getBytes()

您应该将您的密文转换为无损的字符串形式,如十六进制或Base64。所以,试着:

out.println(DatatypeConverter.printHexBinary(encrypted));
byte[] decrypted = cipher.doFinal(DatatypeConverter.parseHexBinary(line));
 类似资料: