O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required