Articles in categories

Articles

Encryption class C#

An Encryption - Decryption class. I use it to encrypt a user's password in the config file. I found this on the internet sometime ago, don't remember where though.
It has only two methods, encrypt and decrypt which take two parameters.

  • the string to en - or decrypt
  • the safety key

This algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits.
key.Length minimum 16 = 128bit (16 * 8 = 128)
key.Length maximum 24 = 192bit (24 * 8 = 192)

using System;
using System.Security.Cryptography;
using System.Text;

namespace Stieven.Helpers
{
  public static class Encryption
  {
    // This algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits.
    // key.Length 16 = 128bit (16 * 8 = 128)
    // key.Length 24 = 192bit (24 * 8 = 192)

    /// <summary>
    /// Encrypt a string with a key
    /// </summary>
    public static string Encrypt(string pwd, string key)
    {
      byte[] inputArray = Encoding.UTF8.GetBytes(pwd);
      byte[] resultArray;
      using (var tripleDes = new TripleDESCryptoServiceProvider())
      {
        tripleDes.Key = Encoding.UTF8.GetBytes(key);
        tripleDes.Mode = CipherMode.ECB;
        tripleDes.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = tripleDes.CreateEncryptor();
        resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
        tripleDes.Clear();
      }
      return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    /// <summary>
    /// Decrypt a string with a key
    /// </summary>
    public static string Decrypt(string pwd, string key)
    {
      if (pwd != null)
      {
        byte[] inputArray = Convert.FromBase64String(pwd);
        byte[] resultArray;
        using (var tripleDes = new TripleDESCryptoServiceProvider())
        {
          tripleDes.Key = Encoding.UTF8.GetBytes(key);
          tripleDes.Mode = CipherMode.ECB;
          tripleDes.Padding = PaddingMode.PKCS7;
          ICryptoTransform cTransform = tripleDes.CreateDecryptor();
          resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
          tripleDes.Clear();
        }
        return Encoding.UTF8.GetString(resultArray);
      }
      return string.Empty;
    }
  }
}

Usage:

string testEncrypt = Encryption.Encrypt(regularString, "12345AbCdEfGhIjK"); // sample key
string testDecrypt = Encryption.Decrypt(encryptedString, "12345AbCdEfGhIjK"); // sample key