Here is a code snippet to help you encrypt and decrypt a string in C#.
The key is hardcoded, but in your own project you may want to read it from a secure store, or perhaps a config file or environment variable.
Notice that the key is being hashed for an extra layer of security.
using System;
using System.Security.Cryptography;
using System.Text;
namespace Crypto
{
class Program
{
static string key { get; set; } = "A!9HHhi%XjjYY4YP2@Nob009X";
static void Main(string[] args)
{
var text = "This is a test string";
Console.WriteLine(text);
var cipher = Encrypt(text);
Console.WriteLine(cipher);
text = Decrypt(cipher);
Console.WriteLine(text);
Console.ReadKey();
}
public static string Encrypt(string text)
{
using (var md5 = new MD5CryptoServiceProvider())
{
using (var tdes = new TripleDESCryptoServiceProvider())
{
tdes.Key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
using (var transform = tdes.CreateEncryptor())
{
byte[] textBytes = UTF8Encoding.UTF8.GetBytes(text);
byte[] bytes = transform.TransformFinalBlock(textBytes, 0, textBytes.Length);
return Convert.ToBase64String(bytes, 0, bytes.Length);
}
}
}
}
public static string Decrypt(string cipher)
{
using (var md5 = new MD5CryptoServiceProvider())
{
using (var tdes = new TripleDESCryptoServiceProvider())
{
tdes.Key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
using (var transform = tdes.CreateDecryptor())
{
byte[] cipherBytes = Convert.FromBase64String(cipher);
byte[] bytes = transform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
return UTF8Encoding.UTF8.GetString(bytes);
}
}
}
}
}
}
And here is the output:
This is a test string
S6HLAUmPMGBPKVT5qVbyuFNQhMTA9/UY
This is a test string