14.2. Encrypting/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 following class, CryptoString, contains two static methods to encrypt and decrypt a string and two static properties to retrieve the generated key and inititialization vector (IV—a random number used as a starting point to encrypt data) after encryption has occurred:

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[] originalStrAsBytes = Encoding.ASCII.GetBytes(originalStr); ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.