views:

1937

answers:

3

Does anyone have any examples of how to encrypt serialized data to a file and then read it back using DES?

I've written some code already that isn't working, but I'd rather see a fresh attempt instead of pursuing my code.

EDIT: Sorry, forgot to mention I need an example using XmlSerializer.Serialize/Deserialize.

A: 

Here is an example of DES encryption/decription for a string.

Yacoder
Sorry, I need an example using XmlSerializer. I'll amend the main question.
GenericTypeTea
+3  A: 

Encryption

public static void EncryptAndSerialize(string filename, MyObject obj, SymmetricAlgorithm key)
{
    using(FileStream fs = File.Open(filename, FileMode.Create))
    {
        using(Cryptostream cs = new CryptoStream(fs, key.CreateEncryptor(), CryptoStreamMode.Write))
        {
            XmlSerializer xmlser = new XmlSerializer(typeof(MyObject));
            xmlser.Serialize(cs, obj); 
        }
    }
}

Decryption:

public static MyObject DecryptAndDeserialize(string filename, SymmetricAlgorithm key)    
{
    using(FileStream fs = File.Open(filename, FileMode.Open))
    {
        using(Cryptostream cs = new CryptoStream(fs, key.CreateDecryptor(), CryptoStreamMode.Read))
        {
            XmlSerializer xmlser = new XmlSerializer(typeof(MyObject));
            return (MyObject) xmlser.Deserialize(cs);
        }
    }
}

Usage:

DESCryptoServiceProvider key = new DESCryptoServiceProvider();
MyObject obj = new MyObject();
EncryptAndSerialize("testfile.xml", obj, key);
MyObject deobj = DecryptAndDeserialize("testfile.xml", key);

You need to change MyObject to whatever the type of your object is that you are serializing, but this is the general idea. The trick is to use the same SymmetricAlgorithm instance to encrypt and decrypt.

Bryce Kahle
Looks like we posted about the same time, I'll accept as it's near enough what I actually wanted! Thanks Bryce.
GenericTypeTea
A: 

Just one question.

If you need to use the same SymmetricAlgorithm instance to decrypt your data, how do you decrypt your file at a later time or from another application?

A.Russell
Welcome to StackOverflow, I suggest you read the FAQ (http://stackoverflow.com/faq). This should be a comment on the original question, not an answer.
GenericTypeTea