我在两个套接字之间加密和解密流时遇到问题。
ObjectInputStream oIn = new ObjectInputStream(new FileInputStream(new File("key")));
SecretKeySpec spec = (SecretKeySpec) oIn.readObject();
//'key' file was saved previously
Cipher cEncrypt = Cipher.getInstance("AES");
cEncrypt.init(Cipher.ENCRYPT_MODE, spec);
Cipher cDecrypt = Cipher.getInstance("AES");
cDecrypt.init(Cipher.DECRYPT_MODE, spec);
//should have no problems here, I tried the ciphers out by encoding and decoding a String, works fine
ObjectOutputStream objectOutputStream= new ObjectOutputStream(new CipherOutputStream(socket.getOutputStream,cEncrypt));
objectOutputStream.flush();
ObjectInputStream objectInputStream = new ObjectInputStream(new CipherInputStream(socket.getInputStream,cDecrypt));
然后,程序停止。套接字两侧的代码相同。在不使用加密流的情况下,程序可以很好地传输数据。
非常感谢任何帮助,谢谢!
答案 0 :(得分:1)
请参阅CipherOutputStream.flush()
:
封装的密码缓冲并等待它处理的任何字节都不会被写出。例如,如果封装的密码是块密码,并且使用其中一种写入方法写入的总字节数小于密码的块大小,则不会写出任何字节。
基本上,您的数据只能以16字节的块写出,因为您使用的是块密码,如ECB或CBC。您可以使用 stream 密码来避免此问题。有关详细信息,请参阅block ciphers modes of operation。您需要选择CFB,OFB或CTR。例如。当你得到Cipher
个实例时:
Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");