gpt4 book ai didi

java - 从套接字创建密码流时应用程序死锁

转载 作者:行者123 更新时间:2023-12-01 15:52:18 24 4
gpt4 key购买 nike

我在加密和解密两个套接字之间的流时遇到问题。

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

然后,程序停止。 socket 两侧的代码相同。在不使用加密流的情况下,程序可以很好地传输数据。

非常感谢任何帮助,谢谢!

最佳答案

参见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.

基本上,您的数据只能以 16 字节的 block 形式写出,因为您使用的是 ECB 或 CBC 等 block 密码。您可以使用密码来避免此问题。请参阅block ciphers modes of operation了解详情。您需要选择 CFB、OFB 或 CTR。例如。当您获得 Cipher 实例时:

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

关于java - 从套接字创建密码流时应用程序死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5777105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com