
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Encrypting and Decrypting a String
|
949
See Also
See Design Patterns (Addison-Wesley).
17.2 Encrypting and Decrypting a String
Problem
You have a string you want to be able to encrypt and decrypt—perhaps a password
or software key—which will be stored in some form accessible by users, such as in a
file, the registry, or even a field, that may be open to attack from malicious code.
Solution
Encrypting the string will prevent users from being able to read and decipher the
information. The
CryptoString class shown in Example 17-5 contains two static
methods to encrypt and decrypt a string and two static properties to retrieve the gen-
erated key and inititialization vector (IV—a random number used as a starting point
to encrypt data) after encryption has occurred.
Example 17-5. CryptoString class
using System;
using System.Security.Cryptography;
public sealed class CryptoString
{
private CryptoString( ) {}
private static byte[] savedKey = null;
private static byte[] savedIV = null;
public static byte[] Key
{
get { return savedKey; }
set { savedKey = value; }
}
public static byte[] IV
{
get { return savedIV; }
set { savedIV = value; }
}
private static void RdGenerateSecretKey(RijndaelManaged rdProvider)
{
if (savedKey == null)
{
rdProvider.KeySize = 256;
rdProvider.GenerateKey( );