简体   繁体   中英

How to write encrypted data to a text file?

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?

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.

有关AES + CBC Java示例的示例,请参见如何附加到AES加密文件 ,该示例允许打开一个已加密的文件并将更多的加密数据附加到in中,同时在解密时不需要任何特殊处理,因为它看起来就像整个文件仅被加密一次。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM