简体   繁体   English

如何将加密数据写入文本文件?

[英]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. 我有一个项目,我们每5分钟向文件写入少量数据。 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. 我们已经有了一种加密方案,可以通过DataI / O流以字节[]数组的形式在网络上发送此数据。

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? 我的问题是,是否可以通过一种方式将加密的byte []数组写入文本文件,以便可以将它们读出来? My biggest problem at the moment is that I'm reading Strings from the files, which messes up the byte[] arrays. 目前,我最大的问题是我正在从文件中读取字符串,这弄乱了byte []数组。

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: 如果要将多个字节数组写入单个文件,则可能应该执行以下操作,因为您正在使用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] [后续数组的长度] [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中,同时在解密时不需要任何特殊处理,因为它看起来就像整个文件仅被加密一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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