Crizly
Crizly

Reputation: 1009

Overwriting Plaintext File With Ciphertext

I've got this function that encrypts a file, the encryption bit seems to be working, but i can't get it to overwrite the current file.

    FileInputStream inputStream = new FileInputStream(input); // Selects file to encrypt

    cipher.init(Cipher.ENCRYPT_MODE, secret, ivSpec); // Sets up the encryption  

    // Creates an the output stream, the encryption is performed here           
    CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(input + ".secure"), cipher);

    byte[] block = new byte[8];
    int i;

    while ((i = inputStream.read(block)) != -1) // Reads the file 
    {
        cos.write(block, 0, i); // Writes the new file
    }

    cos.close();

This is working fine, i end up with an encrypted file with original_file_name.txt.secure, but i want it to overwrite the original file. If i remove the .secure bit it doesn't write the file properly.

How can I overwrite the file original file with the encrypted text?

Upvotes: 0

Views: 99

Answers (1)

chiastic-security
chiastic-security

Reputation: 20520

If you remove the .secure part, you'll be trying to read from the file at the same time that you're writing to it. This is not a very good idea...

The best approach would be to do as you've done, and then if all has gone well, you can delete the original file and rename the old one to match its name, using Files.move().

In fact, if you pass the right options to Files.move(), you can get it to overwrite the existing file, meaning that you won't need to delete the original first.

This solves the simultaneous read/write problem you're having, but it's also a whole lot safer for an application like this. If your application crashes or there's a power cut in the middle of encrypting, and you're encrypting in place, then you're completely screwed. If you do it this way, then power failure in the middle still leaves you with your old file intact. You'll always have the complete old file around until the complete new file is ready.

By the way, you should make use of a BufferedInputStream too, rather than just using a raw FileInputStream. And I can't see an inputStream.close() anywhere.

Upvotes: 1

Related Questions