问题
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