java - Overwriting Plaintext File With Ciphertext -
java - Overwriting Plaintext File With Ciphertext -
i've got function encrypts file, encryption bit seems working, can't overwrite current file.
fileinputstream inputstream = new fileinputstream(input); // selects file encrypt cipher.init(cipher.encrypt_mode, secret, ivspec); // sets encryption // creates output stream, encryption 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 file { cos.write(block, 0, i); // writes new file } cos.close();
this working fine, end encrypted file original_file_name.txt.secure
, want overwrite original file. if remove .secure
bit doesn't write file properly.
how can overwrite file original file encrypted text?
if remove .secure
part, you'll trying read file @ same time you're writing it. not idea...
the best approach you've done, , if has gone well, can delete original file , rename old 1 match name, using files.move()
.
in fact, if pass right options files.move()
, can overwrite existing file, meaning won't need delete original first.
this solves simultaneous read/write problem you're having, it's whole lot safer application this. if application crashes or there's powerfulness cutting in middle of encrypting, , you're encrypting in place, you're screwed. if way, powerfulness failure in middle still leaves old file intact. you'll have finish old file around until finish new file ready.
by way, should create utilize of bufferedinputstream
too, rather using raw fileinputstream
. , can't see inputstream.close()
anywhere.
java encryption file-io
Comments
Post a Comment