How to save class object to file and then encrypt it with open and closed key.
closed key mu开发者_运维百科st be one for all (just for safe)
and open key must be different for each file.
I want use this code ... Looking like it is what I want but I still need Encryption.
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
}
}
}
to moderators : please don't remove C# tag, because I'm able to get C# answer and there is low chances to get nemerle answer :)
There is no standard library in .Net for this (at least none that I know of). But you could follow these principles:
You have 2 keys. Wether symmetric (AES) or asymmetric (Public & private key). Key 1 is closed, key 2 is open.
For every file you create a 3rd key, this key is typically a symmetric (AES) key. This key you encrypt with key 1 and key 2, and the result of these 2 encryptions you store in the header of the file. With key 3 you encrypt your data.
To read, you can choose key 1 or key 2 to decrypt the key you need (key 3) to read the contents of the file.
The System.Security.Cryptography namespace contains all you need.
精彩评论