Rijndael Binary Encryption Writer and Decryption Reader - Jonathan Sawyer

Rijndael Binary Encryption Writer and Decryption Reader

I just found this code very simple. There are a lot of people who have problems with this on the net so decided to post it. Its based on the RijndaelManager and serializes and encrypts the data to a file. It also allow for deserializing and decryption of data. Checkout wikipedia for an explanation of Rijndael http://en.wikipedia.org/wiki/Advanced_Encryption_Standard

 

public static class RijndaelManagedBinaryConvertor

{

private static byte[] Key = { .... your key };
private static byte[] IV = { ..... your IV };
public static void EncryptDataToFile(List<MyObjects> myObjects, string path)
{
try

{

RijndaelManaged rijndael = new RijndaelManaged();
ICryptoTransform encryptor = rijndael.CreateEncryptor(Key, IV);
BinaryFormatter formatter =
new BinaryFormatter();
Stream output = File.Open(path, FileMode.Create);
CryptoStream cryptoOutput =
new CryptoStream(output, encryptor, CryptoStreamMode.Write);
formatter.Serialize(cryptoOutput, myObjects);
cryptoOutput.FlushFinalBlock();
cryptoOutput.Close();
output.Close();

}
catch (CryptographicException cryptographicException)

{

throw new Exception(String.Format("An exception occured while encrpting file Path {0}. Exception {1}", path, cryptographicException.Message));

}

catch (Exception exception)

{

throw new Exception(String.Format("An exception occured while encrpting file Path {0}. Exception {1}", path, exception.Message));

}

}

public static List<MyObjects> DecryptDataFromFile(string path)

{

try

{

RijndaelManaged rijndael = new RijndaelManaged();
ICryptoTransform decryptor = rijndael.CreateDecryptor(Key, IV);
BinaryFormatter formatter =
new BinaryFormatter();
Stream input = File.Open(path, FileMode.Open);
CryptoStream cryptoInput =
new CryptoStream(input, decryptor, CryptoStreamMode.Read);List<MyObjects> myObjects = formatter.Deserialize(cryptoInput) as List<MyObjects>;
cryptoInput.Close();
input.Close();
return myObjects;
}

catch (CryptographicException cryptographicException)

{

throw new Exception(String.Format("An exception occured while decrpting file Path {0}. Exception {1}", path, cryptographicException.Message));

}

catch (Exception exception)

{

throw new Exception(String.Format("An exception occured while decrpting file Path {0}. Exception {1}", path, exception.Message));

}

}

}

Published Wednesday, February 27, 2008 1:26 PM by jonno

Comments

# Wikipedia &raquo; Rijndael Binary Encryption Writer and Decryption Reader

Pingback from  Wikipedia &raquo; Rijndael Binary Encryption Writer and Decryption Reader

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: