Reputation: 1
I have this code to send encryted data over a network:
s = new Socket(serverAddress, serverPort);
is = s.getInputStream();
os = s.getOutputStream();
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, ClientSocket.clientPrivateKey);
cis = new CipherInputStream(is,decryptCipher);
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, this.serverPublicKey);
cos = new CipherOutputStream(os,encryptCipher);
This code works, but when I try to use CipherOutputStream
to send encrypted data over the network, the data is not sent until I call cos.close()
, but if I close the stream I close the network connection. What is the proper process for sending encrypted data with CipherOutputStream
?
Upvotes: 0
Views: 526
Reputation: 13220
The way I interpret the code is that the Cipher is initialized to encrypt one message with RSAES-PKCS1-v1_5, because according to http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Cipher "RSA" refers to "The RSA encryption algorithm as defined in PKCS #1" which I guess refers the oldest implementation with a padding scheme and that should be RSAES-PKCS1-v1_5. If that is correct, there is no way for the stream to produce partial results before the whole message (the whole stream) is read. Also you should not be able to send long messages with the cipher (with a 2048 bit RSA key that should be less than 256 bytes).
I assume what you are trying to accomplish is to create a secure connection between two endpoints? If so then you should not bother with all that low level cryptography and create a TLS connection. Even though it not trivial to set up it still is much more easier than to build a secure encrypted communication channel from scratch.
Upvotes: 2