如何将类对象保存到文件,然后使用打开和关闭的密钥对其进行加密。
关闭的密钥必须是一个(只是为了安全)
每个文件的和open键必须不同。
我想使用此代码...看起来就像我想要的那样但是我仍然需要加密。
public ObjectToFile(_Object : object, _FileName : string) : bool
{
try
{
// create new memory stream
mutable _MemoryStream : System.IO.MemoryStream = System.IO.MemoryStream();
// create new BinaryFormatter
def _BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
= System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
// Serializes an object, or graph of connected objects, to the given stream.
_BinaryFormatter.Serialize(_MemoryStream, _Object);
// convert stream to byte array
mutable _ByteArray : array[byte] = _MemoryStream.ToArray();
// Open file for writing
def _FileStream : System.IO.FileStream =
System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
// Writes a block of bytes to this stream using data from a byte array.
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);
// close file stream
_FileStream.Close();
// cleanup
_MemoryStream.Close();
_MemoryStream.Dispose();
_MemoryStream = null;
_ByteArray = null;
true
}
catch
{
| e is Exception => // Error
{
Console.WriteLine("Exception caught in process: {0}", e.ToString());
false
}
}
}
主持人:请不要删除C#标签,因为我能够获得C#答案,并且获得nemerle答案的可能性很小:)
答案 0 :(得分:1)
.Net中没有标准库(至少没有我知道的)。但你可以遵循以下原则:
你有2把钥匙。对称(AES)或非对称(公钥和私钥)。钥匙1关闭,钥匙2打开。
对于您创建第三个密钥的每个文件,此密钥通常是对称(AES)密钥。使用密钥1和密钥2加密的密钥,以及存储在文件头中的这2个加密的结果。使用密钥3,您可以加密数据。
要阅读,您可以选择密钥1或密钥2来解密所需的密钥(密钥3)以读取文件的内容。
System.Security.Cryptography命名空间包含您需要的所有内容。