// See https://aka.ms/new-console-template for more information using ConfigurationManager = System.Configuration.ConfigurationManager; using System.Collections.Specialized; using System.Security.Cryptography; using System.Text; namespace aesencrypt; public class Program { static void encrypt(string plainText, string encryptionKey) { byte[] keyBytes = Encoding.UTF8.GetBytes(encryptionKey); using (Aes aes = Aes.Create()) { aes.Key = keyBytes; aes.GenerateIV(); // Always generate a new IV using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV)) { byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length); // Combine IV and encrypted data byte[] combinedBytes = new byte[aes.IV.Length + encryptedBytes.Length]; Buffer.BlockCopy(aes.IV, 0, combinedBytes, 0, aes.IV.Length); Buffer.BlockCopy(encryptedBytes, 0, combinedBytes, aes.IV.Length, encryptedBytes.Length); Console.WriteLine(Convert.ToBase64String(combinedBytes)); } } } static void decrypt(string plainText,string encryptionKey) { byte[] fullCipher = Convert.FromBase64String(plainText); byte[] iv = new byte[16]; byte[] cipher = new byte[fullCipher.Length - iv.Length]; Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length); Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, cipher.Length); byte[] keyBytes = Encoding.UTF8.GetBytes(encryptionKey); using (Aes aes = Aes.Create()) { aes.Key = keyBytes; aes.IV = iv; using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV)) { byte[] decryptedBytes = decryptor.TransformFinalBlock(cipher, 0, cipher.Length); Console.WriteLine(Encoding.UTF8.GetString(decryptedBytes)); } } } static void Main(string[] args) { var Initialconfiguration = ConfigurationManager.GetSection("settings") as NameValueCollection; string function = Initialconfiguration["function"]; string encryptionKeyUsed = Initialconfiguration["key"]; if (function == "encrypt") { Console.WriteLine("What do you want to encrypt?"); encrypt(Console.ReadLine(),encryptionKeyUsed); } else if (function == "decrypt") { Console.WriteLine("What do you want to decrypt?"); decrypt(Console.ReadLine(),encryptionKeyUsed); } else { Console.WriteLine("Invalid function type"); } Console.ReadLine(); } }