Question

I have a project where we write a small amount of data to a file every 5 minutes. The idea is to look at how this data changes over a period of hours, days, and weeks.

One of the requirements is to store this data in a secure format. We already have an encryption scheme for sending this data across a network as a byte[] array via DataI/O streams.

The question I have is this, is there a way to write encrypted byte[] arrays to a text file in such a way that I can read them back out? My biggest problem at the moment is that I'm reading Strings from the files, which messes up the byte[] arrays.

Any thoughts or pointers on where to go?

Was it helpful?

Solution

What you need to do is take your data and put it into a byte array. Then once it is in a byte array, you can encrypt it using an encryption algorithm. Then you write it to the file.

When you want to get the original data back, you have to read the byte array from the file, then decrypt the byte array and then you will have your original data. You cannot just read this data as a string because your encryption algorithm will create bytes that cannot be represented as regular chars so your data will get messed up.

Just make sure you read the encrypted data as a byte array and not a string, that is where you are having a problem.


If you want to write multiple byte arrays to a single file, then you should probably do something like this since you are using Java:

writer.print(arr.length);
writer.print(arr);
writer.flush();

Do this for each byte array. Then when you read the byte arrays back:

int length = reader.readInt();
byte[] bytes = new byte[length];
// fill array

This way the file can be structured like this:

[length of following array][array][length of second array][second array]

You will be able to put all of the byte arrays back to back, and since each array starts with the length of the array, you will know how much data needs to be put into each array.

OTHER TIPS

See How to append to AES encrypted file for an example of an AES+CBC Java example which allows opening an already encrypted file and appending more encrypted data to in, while not requiring any special handling when decrypting it since it looks just like it would if the entire file had been encrypted just once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top