tags:

views:

50

answers:

1

How to save class object to file and then encrypt it with open and closed key.

closed key must 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 :)

+1  A: 

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.

GvS
I can understand the stuff with a keys... But I need some working method (some code) some examples of encryption. I also though .net got some libraries so I'm wondering if not.
nCdy
A lot of code examples are on MSDN (example: http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.aspx). .Net contains classes for encryption, but not for this specific problem domain.
GvS