Application deadlocks when creating cipher streams from socket

无人久伴 提交于 2019-12-05 10:51:34

问题


I'm having problems encrypting and decrypting my streams between two sockets.

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));

Then, the program stops. The code is the same on both sides of the socket. Without using ciphered streams, the program transfers data fine.

Any help is much appreciated, thanks!


回答1:


See CipherOutputStream.flush():

Any bytes buffered by the encapsulated cipher and waiting to be processed by it will not be written out. For example, if the encapsulated cipher is a block cipher, and the total number of bytes written using one of the write methods is less than the cipher's block size, no bytes will be written out.

Basically your data can only be written out in chunks of 16 bytes because you're using a block cipher like ECB or CBC. You can avoid this problem by using a stream cipher. See block ciphers modes of operation for details. You'll need to select CFB, OFB or CTR. E.g. when you get your Cipher instance:

Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");


来源:https://stackoverflow.com/questions/5777105/application-deadlocks-when-creating-cipher-streams-from-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!