C# 在写入磁盘之前加密序列化文件
假设我的程序有一个名为“customer”的类,并且该客户类是可序列化的,因此我可以将其读取和写入磁盘。客户类保存我想要加密的敏感信息,我知道可以保证文件安全的唯一方法是:
1-将文件序列化到磁盘
2-重新打开并加载文件
3-加密文件
4-将文件重写到磁盘
这可行,但存在文件可能在未加密状态下被拦截的风险,而且这确实是真的效率低下。
相反,我想:
1-在内存中创建文件
2-加密内存中的文件
3-将加密文件写入磁盘
这可能吗?如果是怎么办?提前致谢。
Let's say my program has a class called "customer" and the customer class is serializable so I can read and write it to disk. The customer class holds sensitive information that I want to encrypt, the only way I know I could keep the file safe would be to:
1-Serialize the file to disk
2-Reopen and load the file
3-Encrypt the file
4-Rewrite file to disk
This would work, but there is a risk that the file could be intercepted in it's unencrypted state and furthermore this is just really inefficient.
Instead I would like to:
1-Create file in memory
2-Encrypt file in memory
3-Write encrypted file to disk
Is this possible? If it is how? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在将类序列化到文件的同时使用 CryptoStream 进行加密:
You can use a CryptoStream to do the encryption at the same time as you serialize the class to a file:
除了评论中表达的担忧之外,如果您所问的只是如何使用内存中的字节并且仅将它们写入文件一次,那么只需首先将对象序列化到内存流即可。加密这些字节并将其写入文件。
Aside from the concerns expressed in the comments, if all you are asking is how to work with the bytes in memory and only write them to the file once, just serialize your object to a memory stream first. Encrypt those bytes and write them to the file.
很有可能,
假设您的类看起来像
您可以加密对象属性中保存的数据
所以 customer.Name = 'ABC' 可能会变成 customer.Name = 'WQW' 类似的东西
而不是序列化它。
在反序列化时,当您必须显示数据时,您必须在向用户显示数据之前对其进行解密
希望这有帮助
Its quite possible,
Lets say you class looks like
You could encrypt the data held in properties of the object
so customer.Name = 'ABC' could become customer.Name = 'WQW' something like that
than serialize it.
On deserialization, when you have to show the data you have to decrypt it before showing the data to the user
hope this help
我将创建一个提供属性的序列化类。读取它(给出文件名)会返回反序列化的对象,写入它(也给出文件名)会序列化对象。
我添加了第二个带有字符串密码的属性。使用它时,您可以加密序列化对象字符串和 nwrite 到磁盘,或者从其中读取时 1. 加密,然后反序列化。
为了加密,我建议使用密码的哈希函数,而不是直接使用它。
不幸的是,我在 vb.net 中只有一个代码示例:
并且
我的代码中的属性有 Get:
和 Set:
您必须定义自己的序列化,并读取/写入文件:
I would create a class for serialization which offers a property. reading it (giving a filename) returns the deserialized objects, writing to it (also giving a filename) serializes the object.
I added a second property with a String password. When using it you can encrypt the serialized object string and the nwrite to disk or when reading from it 1. encrypt, then deserialize.
To encrypt, I would recommend a hash function from the password instead of directly using it.
Unfortunately I only have a code example in vb.net:
and
the property in my code has Get:
and Set:
you will have to define your own Serialization, and to read/write Files: