I'm trying to write some bytes to a Gzip-compressed and ChaCha20-encrypted output stream to recreate an HmacBlock of a KDBX4 file. Below is how I declare and initialize the streams:
//needed for determining # of bytes written and resetting to 0 bytes when a certain amount are written
private ByteArrayOutputStream blockCipherTextOutputStream = new ByteArrayOutputStream();
//wraps blockCipherTextOutputStream
//bytes written here are ChaCha20 encrypted
private OutputStream encryptedOutputStream;
//wraps encryptedOutputStream
//bytes written here are in little-endian order
private LittleEndianDataOutputStream ledos;
//creating a CipherOutputStream initialized with ChaCha20 encryption
//sets blockCipherTextOutputStream as the underlying OutputStream to be written to
encryptedOutputStream = kdbxHeader.createEncryptedStream(credentials.getKey(), blockCipherTextOutputStream);
//the OutputStream that writes directly to the file
//bytes eventually get written here in other methods
private OutputStream outputStream;
if(kdbxHeader.getCompressionFlags().equals(KdbxHeader.CompressionFlags.GZIP)) {
/*
* this seems to be adding 10 bytes to the stream to start
* writing to the stream seemingly does nothing afterwards
*/
encryptedOutputStream = new GZIPOutputStream(encryptedOutputStream);
}
ledos = new LittleEndianDataOutputStream(encryptedOutputStream);
When creating the encrypted output stream, a method is called in the KdbxHeader class which in turn calls to a method in another class called ChaCha. Below is the method in ChaCha which actually creates (and returns) an encrypted output stream:
@Override
public OutputStream getEncryptedOutputStream(OutputStream decryptedOutputStream, byte[] key, byte[] iv) {
final ParametersWithIV keyAndIV = new ParametersWithIV(new KeyParameter(key), iv);
StreamCipher cipher = new ChaCha7539Engine();
cipher.init(true, keyAndIV);
return new CipherOutputStream(decryptedOutputStream, cipher);
}
Hopefully that's enough code to go on, I can add more if necessary but this is part of a larger API so there is a lot going on. encryptedOutputStream
only starts (and doesn't expand from) 10 bytes when I try to compress it; otherwise, it starts empty (as it should) and I can write to it.
Even after initializing blockCipherTextOutputStream
with a buffer size of 80000, the write attempts still don't seem to do anything as only the 10 bytes in encryptedOutputStream
to start are visible in a hex editor. Why is this happening and what am I doing wrong here?