Basic Encryption/Decryption (C#)
This example shows how you can use C# to encrypt and decrypt strings using a salt key to protect the data.
This type of encryption is called symmetric-key encryption, which means that the string can only be decrypted if the other party has the correct key.
using System.Security.Cryptography;
using System.Text;
public static class Encryption
{
public static string Encrypt(string input, string key)
{
byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
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);
}
public static string Decrypt(string input, string key)
{
byte[] inputArray = Convert.FromBase64String(input);
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);
}
}
4 thoughts on “Basic Encryption/Decryption (C#)”
Leave a Reply
You must be logged in to post a comment.
[...] les classes de cryptage et décryptage que j’ai récupéré sur ici : Source code public static string Encrypt(string input, string key) [...]
[...] Anyhow, I’ve used this encryption method [...]
[...] Encrypt Decrypt Posted on Ekim 31, 2012 by Selçuk http://www.deltasblog.co.uk/code-snippets/basic-encryptiondecryption-c/ using System; using System.Security.Cryptography; using System.Text;public static class Encryption [...]
[...] on the internet to find an encryption utility class in .NET. I found the following algorithm at http://www.deltasblog.co.uk/code-snippets/basic-encryptiondecryption-c/, and put it within a class that adheres to my IEncryptor interface [...]