Supertext Home
Chief of the System Blog

Simple C# encryption and decryption

January 20th, 2011 by

There are various ways to encrypt and decrypt a string in with .Net. The simplest is to use Base64. But this just makes the string unreadable for a human, but it is not a real encryption. Although, for most case is is likely enough.

If you want something a little fancier, I have a simple solution for you:

 

public static String Encrypt(string source)
{
   
DESCryptoServiceProvider des = new DESCryptoServiceProvider
();
   
byte
[] Key = { 12, 13, 14, 15, 16, 17, 18, 19 };
   
byte
[] IV =  { 12, 13, 14, 15, 16, 17, 18, 19 };

    ICryptoTransform encryptor = des.CreateEncryptor(Key, IV);

    try
    {
       
byte[] IDToBytes = ASCIIEncoding
.ASCII.GetBytes(source);
       
byte
[] encryptedID = encryptor.TransformFinalBlock(IDToBytes, 0, IDToBytes.Length);
       
return Convert
.ToBase64String(encryptedID);
    }
   
catch (FormatException
)
    {
       
return null
;
    }
   
catch (Exception
)
    {
       
throw
;
    }
}


public static string Decrypt(string
encrypted)
{
   
byte
[] Key = { 12, 13, 14, 15, 16, 17, 18, 19 };
   
byte
[] IV =  { 12, 13, 14, 15, 16, 17, 18, 19 };

    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
   
ICryptoTransform
decryptor = des.CreateDecryptor(Key, IV);

    try
    {
       
byte[] encryptedIDToBytes = Convert
.FromBase64String(encrypted);
       
byte
[] IDToBytes = decryptor.TransformFinalBlock(encryptedIDToBytes, 0, encryptedIDToBytes.Length);
       
return ASCIIEncoding
.ASCII.GetString(IDToBytes);
    }
   
catch (FormatException
)
    {
       
return
null;
    }
   
catch (Exception
)
    {
       
throw
;
    }
}

Just make sure that you replace the Key and IV values.

I had to use the  Base64 Encoding in addition to the encryption so you can use the result string like a normal string and write it somewhere. Otherwise it could contain non ASCII characters and you couldn’t easily use it.

 

If you want to use the encrypted string in a url, you should HTML encode it too:

System.Web.HttpUtility.UrlEncode(Encrypt(mystring));
 

Have fun and let me know if you have any questions.

Related Posts

  1. The .NET TimeZoneInfo GetSystemTimeZones() List
  2. The Supertext REST API
  3. World Domination…
  4. Getting started with a Windows 8 Store App

Leave a Reply

  • Topics
  • Archive
  • Subscribe
  • Facebook
  • Twitter