find a location for property in a new city

Thursday, 8 September 2011

Triple DES encryption and decryption with .NET

TripleDes essentials

Start your class like this:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Utils
{
 public static class EncryptionHelper
 {
    static private byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                                            15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
    static private byte[] iv8Bit = { 1,2,3,4,5,6,7,8 };

TripleDes Encryption

Add the following method for encrypting with Triple DES:
public static string TripleDesEncryption(string dataToEncrypt)
{
   var bytes = Encoding.Default.GetBytes(dataToEncrypt);
   using (var tripleDes= new TripleDESCryptoServiceProvider())
   {
    using (var ms = new MemoryStream())
    using (var encryptor = tripleDes.CreateEncryptor(key, iv8Bit))
    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
    {
     cs.Write(bytes, 0, bytes.Length);
     cs.FlushFinalBlock();
     var cipher = ms.ToArray();
     return Convert.ToBase64String(cipher);
    }
   }
}

Triple DES Decryption

The next method will allow decryption of your data
public static string TripleDesDecryption(string dataToDecrypt)
{
   var bytes = Convert.FromBase64String(dataToDecrypt);
   using (var tripleDes= new TripleDESCryptoServiceProvider())
   {
    using (var ms = new MemoryStream())
    using (var decryptor = tripleDes.CreateDecryptor(key, iv8Bit))
    using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
    {
     cs.Write(bytes, 0, bytes.Length);
     cs.FlushFinalBlock();
     var cipher = ms.ToArray();
     return Encoding.UTF8.GetString(cipher);
    }
   }
}

Follow britishdev on Twitter

No comments:

Post a Comment