
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Encrypting and Decrypting a String
|
951
Discussion
The CryptoString class contains only static members, except for the private instance
constructor, which prevents anyone from directly creating an object from this class.
This class uses the Rijndael algorithm to encrypt and decrypt a string. This algorithm
is found in the
System.Security.Cryptography.RijndaelManaged class. This algorithm
requires a secret key and an initialization vector; both are
byte arrays. A random
secret key can be generated for you by calling the
GenerateKey method on the
// Convert encrypted string.
string encryptedStr = Convert.ToBase64String(originalBytes);
return (encryptedStr);
}
public static string Decrypt(string encryptedStr)
{
// Unconvert encrypted string.
byte[] encryptedStrAsBytes = Convert.FromBase64String(encryptedStr);
byte[] initialText = new Byte[encryptedStrAsBytes.Length];
using (RijndaelManaged rijndael = new RijndaelManaged( ))
{
using (MemoryStream memStream = new MemoryStream(encryptedStrAsBytes))
{
if (savedKey == null || savedIV == null)
{
throw (new NullReferenceException(
"savedKey and savedIV must be non-null."));
}
// Create decryptor, and stream objects.
using (ICryptoTransform rdTransform =
rijndael.CreateDecryptor((byte[])savedKey.
Clone( ),(byte[])savedIV.Clone( )))
{
using ...