using System.Security.Cryptography;
public static void Main()
var encrypt = EncryptString("Server=localhost\\SQLEXPRESS;Database=DynamicCommandExecutor;User Id=sa;Password=xxxx;TrustServerCertificate=True;","connectionstring");
Console.WriteLine(encrypt);
Console.WriteLine(DecryptString(encrypt,"connectionstring"));
public static string EncryptString(string plainText, string key)
using (Aes aes = Aes.Create())
aes.Key = CreateKey(key);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aes.CreateEncryptor();
byte[] inputBytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes = encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
return Convert.ToBase64String(encryptedBytes).Replace('+','-').Replace('/','_');
public static string DecryptString( string cipherText, string key)
using (Aes aes = Aes.Create())
aes.Key = CreateKey(key);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aes.CreateDecryptor();
byte[] cipherBytes = Convert.FromBase64String(cipherText.Replace('-', '+').Replace('_', '/'));
byte[] decryptedBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
return Encoding.UTF8.GetString(decryptedBytes);
static byte[] CreateKey(string key)
using (SHA256 sha256 = SHA256.Create())
return sha256.ComputeHash(Encoding.UTF8.GetBytes(key));