I need to encrypt and send data via TCP (from several 100 bytes to several 100 megabytes per message) in pieces from Java to C ++ program and I need to send the data size in advance so that the recipient knows when to stop reading the current message and process it, and then wait for the next message (the connection remains open, so there is no other way to indicate the end of the message, since the data may be binary, I can not use the flag to indicate the end of the message due to the possibility that the encrypted bytes may accidentally ok identical to any selected flag at any point).
My problem is to calculate the size of the encrypted message before encrypting it, which in general will be different from the input length due to filling, etc.
Let's say I was initialized as follows:
AlgorithmParameterSpec paramSpec = new IvParameterSpec(initv);
encipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
mac = Mac.getInstance("HmacSHA512");
encipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
mac.init(key);
buf = new byte[encipher.getOutputSize(blockSize)];
Then I send the data as such (and also have a similar function that uses the stream to enter instead byte[]):
public void writeBytes(DataOutputStream out, byte[] input) {
try {
int left = input.length;
int offset = 0;
while (left > 0)
{
int chunk = Math.min(left, blockSize);
int ctLength = encipher.update(input, offset, chunk, buf, 0);
mac.update(input, offset, chunk);
out.write(buf, 0, ctLength);
left -= chunk;
offset += chunk;
}
out.write(encipher.doFinal(mac.doFinal());
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
, ?
, out.writeInt(messageSize) . messageSize? Cipher getOutputSize() , " () ". , , update() doFinal()... , blockSize AES CBC, , ? , _blockSize % encipher.getOutputSize(1) != 0,
int messageSize = (input.length / blockSize) * encipher.getOutputSize(blockSize) +
encipher.getOutputSize(input.length % blockSize + mac.getMacLength());
??
, ?