December 2007
Intermediate to advanced
896 pages
19h 57m
English
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, such as in a file or the registry. You want to keep this string a secret so that users cannot take this information from you.
Encrypting the string will help to 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 generated key and initialization 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( ); savedKey = rdProvider.Key; } } private static void RdGenerateSecretInitVector(RijndaelManaged rdProvider)< { if (savedIV == null) { rdProvider.GenerateIV(); savedIV = rdProvider.IV; } } public static string Encrypt(string originalStr) { // Encode data string to be stored in memory. byte[] ...Read now
Unlock full access