Skip to content

Instantly share code, notes, and snippets.

@TheAlphamerc
Last active September 18, 2018 06:29
Show Gist options
  • Save TheAlphamerc/de7c5f24a1c0721b2b4a4a02b89ea8d0 to your computer and use it in GitHub Desktop.
Save TheAlphamerc/de7c5f24a1c0721b2b4a4a02b89ea8d0 to your computer and use it in GitHub Desktop.
Code to encrypt/decrypt string using key
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
namespace Helpers
{
public class EncryptData
{
/// <summary>
/// Defines the key for encryption and decryption
/// </summary>
public static string Key = "MyKey";
/// <summary>
/// Encrypt method use key to encrypt string
/// </summary>
/// <param name="inputString">inputString<see cref="string"/></param>
/// <returns>inputString <see cref="string"/></returns>
public static string Encrypt(string inputString)
{
byte[] inputArray = UTF8Encoding.UTF8.GetBytes(inputString);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(Key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
/// <summary>
/// Decrypt method use key to decrypt string
/// </summary>
/// <param name="inputString">inputString<see cref="string"/></param>
/// <returns>inputString <see cref="string"/></returns>
public static string Decrypt(string inputString)
{
byte[] inputArray = Convert.FromBase64String(inputString);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(Key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment