我正在尝试解密服务器上的消息 - 我得到的错误是
使用的加密技术 - DES。
- 线程“main”中的异常javax.crypto.BadPaddingException:给定最终块未正确填充
我正在努力解决这个问题, 任何帮助将不胜感激
class TCPServer {
public static void main(String argv[]) throws Exception {
String password = null;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
password = "Passcode";
byte[] salt = new byte[64];
Random rnd = new Random();
rnd.nextBytes(salt);
byte[] data = deriveKey(password, salt, 64);
byte [] EncyptedText = inFromClient.readLine().getBytes();
System.out.println("Received Encrypted message " + EncyptedText);
SecretKey desKey = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(data));
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, desKey);
// Decrypt the text
System.out.println("Text Received " + EncyptedText);
byte[] textDecrypted = cipher.doFinal(EncyptedText);
System.out.println("Text Decryted : " + new String(textDecrypted));
}
}
public static byte[] deriveKey(String password, byte[] salt, int keyLen) {
SecretKeyFactory kf = null;
try {
kf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeySpec specs = new PBEKeySpec(password.toCharArray(), salt, 1024, keyLen);
SecretKey key = null;
try {
key = kf.generateSecret(specs);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return key.getEncoded();
}
}
服务器端代码
unserialize()
答案 0 :(得分:0)
这样做会丢失数据:
outToServer.writeBytes(new String(textEncrypted) + '\n');
除此之外,没有必要。密文不是现代密码的真正文本,它是二进制文件。由于套接字提供二进制InputStream
和OutputStream
,因此根本没有理由将密文转换为字符串。所需要的只是将可能的输入字符串转换为二进制(当然在客户端和服务器上使用相同的编码 - 现在首选UTF-8)。