Website development and design blog, tutorials and inspiration

Simple String Encryption and Decryption with C#

Encrypt and decrypt information using .Net cryptography tools

By , 19th October 2011 in C#

In this tutorial, we will look at implementing the cryptography object in C# to encrypt and decrypt information, either passwords or connection strings and prevent unauthorised eyes from prying at your passwords.

Due to bizarre and strange legal issues, we are unable to go into any detail regarding the actual techniques involved during the encryption process, however, we can use the classes provided by Microsoft to encrypt our data. We have an article which can give you an overview of how cryptography works which you may find interesting.

In this article, we will have a look at simple string encryption and decryption with a focus on saving encrypted connection strings in the web.config or app.config files.

There are two methods for encrypting data in the web.config. There is a manual way and an automatic way. To start with we will look at manually encrypting the connection string.

  1. string conStr = "Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;";

This is a typical connection string to a SQL server with a username and password. This is not the sort of information that should be accessible but stored like this it can be accessed by anyone who can view the C# source code (not the HTML source code sent to browser unless a coding error includes it.)

It would be far better to encrypt this string so that it is meaningless without a proper decryption. We can do this with a simple base64 encoding which will only be effective against a casual reader and is not secure, or we can implement one of the many encryption routines supported by .Net. In this example, we will use the DES method.

All of the encryption methods require binary data as an input and they all return binary data. When you are encrypting strings they will need to be converted to binary beforehand.

  1. // The plain string to encrypt
  2. string plaintextString = "This is an encryption test";
  4. // Binary representation of plain text string
  5. byte[] plaintextBytes = (new UnicodeEncoding()).GetBytes(plaintextString);

Next, we need to create a memory stream to hold the result data and an encryption algorithm.

  1. // Encrypt using DES
  2. SymmetricAlgorithm sa = DES.Create();
  3. MemoryStream msEncrypt = new MemoryStream();
  4. CryptoStream csEncrypt = new CryptoStream(msEncrypt, sa.CreateEncryptor(), CryptoStreamMode.Write);
  5. csEncrypt.Write(plaintextBytes, 0, plaintextBytes.Length);
  6. csEncrypt.Close();
  7. byte[] encryptedTextBytes = msEncrypt.ToArray();
  8. msEncrypt.Close();

Where the encrypted data is now stored within encryptedTextBytes. Decryption is the reverse procedure using a decryption algorithm.

  1. MemoryStream msDecrypt = new MemoryStream(encryptedTextBytes);
  2. CryptoStream csDecrypt = new CryptoStream(msDecrypt, sa.CreateDecryptor(), CryptoStreamMode.Read);
  3. byte[] decryptedTextBytes = new Byte[encryptedTextBytes.Length];
  4. csDecrypt.Read(decryptedTextBytes, 0, encryptedTextBytes.Length);
  5. csDecrypt.Close();
  6. msDecrypt.Close();
  8. string decryptedTextString = (new UnicodeEncoding()).GetString(decryptedTextBytes);

You can now use the encrypted text to store. Note: a password has not been used to encrypt this data, so it can still be decrypted using the machine hash key.

The best solution is to use the automatic section protection feature of .Net. This is done using a WebConfigurationManager and RsaProtectedConfigurationProvider and can protect the entire appsettings section.

  1. using System.Web.Configuration;
  3. private void EncryptAppSettings()
  4. {
  5. Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
  6. AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
  7. if (!objAppsettings.SectionInformation.IsProtected)
  8. {
  9. objAppsettings.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
  10. objAppsettings.SectionInformation.ForceSave = true;
  11. objConfig.Save(ConfigurationSaveMode.Modified);
  12. }
  13. }
  1. private void DecryptAppSettings()
  2. {
  3. Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
  4. AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
  5. if (objAppsettings.SectionInformation.IsProtected)
  6. {
  7. objAppsettings.SectionInformation.UnprotectSection();
  8. objAppsettings.SectionInformation.ForceSave = true;
  9. objConfig.Save(ConfigurationSaveMode.Modified);
  10. }
  11. }

This code will effectively encrypt the entire appSettings section to make it unviewable by people with access to the web server, but should not have access to the settings (i.e. server administrator). Below is a before and after shot of a protected appSettings section.

  1. <appSettings>
  2. <add key="connectionString" value="Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"/>
  3. <add key="test" value="this is a test"/>
  4. </appSettings>
  1. <appSettings configProtectionProvider="RsaProtectedConfigurationProvider">
  2. <EncryptedData Type=""
  3. xmlns="">
  4. <EncryptionMethod Algorithm="" />
  5. <KeyInfo xmlns="">
  6. <EncryptedKey xmlns="">
  7. <EncryptionMethod Algorithm="" />
  8. <KeyInfo xmlns="">
  9. <KeyName>Rsa Key</KeyName>
  10. </KeyInfo>
  11. <CipherData>
  12. <CipherValue>lp1R3ya0BYL9yI/vNYCyErq78X9XPwzUz7GC2ZnZ2/ruo1ESA9cQY7Vy0wVt7u+lRWHZ7iW+nD8qZHW8xIktJNw5lg7bRUcqsCUmIUL0xUv8Miz/MwFR4kBtebk+JGaawzZQYUgW+UcEUW63nVF5J2ERqUDzoqR0GUlySC2tvh4=</CipherValue>
  13. </CipherData>
  14. </EncryptedKey>
  15. </KeyInfo>
  16. <CipherData>
  17. <CipherValue>wkE0pqLLPVEaA1s625vA8nmDlMmsDz0m+UOdJz/g+H+792RwrC9Z/XuufuKnff3W9ovkbNiGt8tBQmctqKkNkj0GXp53SAhmUq6AAy1tsXXBlBxiABIIE/POFlOlWVI3cmZte1b9q7SPRCw6Bh6oHS2GS91O1sGFZUd7SZxK7oiq5FtaQX+97kvhNWTSb6go1dsCoGYbPOUY4FIEvPvxppdR1QLDsJIEme1BiyCi3NcTUkWBfqmFWKCFzZgmZOkU2LjtBPAat9Cix9TEHqnInCYFmotUbBOsA/qk2YsbVSalbIwNDMCR7Q==</CipherValue>
  18. </CipherData>
  19. </EncryptedData>
  20. </appSettings>

You can still use the appSettings as normal, the only change is the way the data is held within the file.

Further Reading

There are no comments for this post. Be the first!

Leave a Reply

Your email address will not be published.