How to store in a file the ciphertext and the IV (of a block cipher mode of operation, e.g. AES-GCM)? If I separate them with a byte corresponding to the ":" character, when reading it I'll have to convert the whole byte array in String and then split the strings into chunks separated by ":" and then again convert the chunks into byte arrays. Is there a simpler way? Maybe a byte that we are sure can't appear as a result of an AES encryption and in a Initialization Vector?
The current code (in Java) is the subsequent, but I'm not sure if it is the best way to perform what I asked and even if it works because I don't know if the byte representing ":" can appear in the IV or the ciphertext.
FileInputStream keyfis = new FileInputStream("test");
byte[] byteRead = new byte[keyfis.available()];
keyfis.read(byteRead);
keyfis.close();
String textRead=new String(byteRead);
String[] parts = textRead.split(":");
byte[] encrAESkey=parts[0].getBytes();
byte[] myIV=parts[1].getBytes();
byte[] myencrtext=parts[2].getBytes();
Traditionally the IV is prepended, as it is required to be exactly one block length (16 bytes
), and block cipher modes (other than ECB) all require the IV (or nonce + counter). Then your decryption code simply extracts the first 16 bytes
from the cipher text input and uses it as the IV, and performs the decryption operation on the remaining n - 16 bytes
.
You should use an encoding scheme to protect the cipher text you serialize to the file however, as you will very likely encounter issues if you write/read raw binary bytes. Hexadecimal or Base64 encoding are the standard for this operation.
It also appears from your code that you are storing the AES key alongside the IV and cipher text. While the IV can be stored unprotected alongside the cipher text, the key cannot without effectively removing any protection that encryption would provide.