0

I'm trying to write code in Java that will encrypt file. I had used example from this site: http://www.avajava.com/tutorials/lessons/how-do-i-encrypt-and-decrypt-files-using-des.html

Everything works fine but I need code that will overwrite original file with encrypted one. I'd changed only this:

FileInputStream fis = new FileInputStream("original.txt");
FileOutputStream fos = new FileOutputStream("original.txt");
encrypt(key, fis, fos);

FileInputStream fis2 = new FileInputStream("original.txt");
FileOutputStream fos2 = new FileOutputStream("original.txt");

Encryption works, but after decryption decrypted file is empty. Can someone explain me what's the problem and how to solve it?

Thanks !

umb
  • 3
  • 2
  • 1
    where are you decrypting? – dev2d Dec 05 '13 at 19:36
  • First off, that's a horrible example to follow. They are doing several things wrong. – erickson Dec 05 '13 at 19:36
  • If you can recommend any good example of encryption in java I'll be grateful – umb Dec 05 '13 at 19:57
  • You should not use a password directly as a key. [This post](http://stackoverflow.com/a/992413/3474) shows how to create a proper key from a password. It uses AES-256, but AES-128 is good enough. DES isn't good enough for anything. You should not use ECB mode. Use CBC mode, and store the IV at the beginning of the encrypted file. I'll try to provide an example of this too. A mode that provides integrity protection would be even better, but baby steps... – erickson Dec 05 '13 at 20:10

1 Answers1

2

You shouldn't read and overwrite the same file simultaneously with FileInputStream and FileOutputStream. Often, you'll get lucky, but the behavior is going to vary based on the underlying system, and that's not good. Instead, write to a temporary file, then move the temporary file to the location of the original file.

erickson
  • 265,237
  • 58
  • 395
  • 493