AES_Encryption_Test/Program.cs

73 lines
2.3 KiB
C#

using System.Security.Cryptography;
using System.Text;
static string Encrypt(string plainText, byte[] secretKey) {
using Aes aes = Aes.Create();
aes.Key = secretKey;
// Convert the plain text string into a byte array
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Create an encryptor using the AES service and its initialization vector (IV)
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
// Perform the encryption
byte[] encrypted = encryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length);
// Create a new byte array to hold the IV and the encrypted data
byte[] result = new byte[aes.IV.Length + encrypted.Length];
// Copy the IV and encrypted data into the result byte array
Buffer.BlockCopy(aes.IV, 0, result, 0, aes.IV.Length);
Buffer.BlockCopy(encrypted, 0, result, aes.IV.Length, encrypted.Length);
return Convert.ToBase64String(result);
}
static string Decrypt(string encryptedText, byte[] secretKey) {
using Aes aes = Aes.Create();
aes.Key = secretKey;
// Decode the base64 string into a byte array
byte[] fullCipher = Convert.FromBase64String(encryptedText);
// Create byte arrays to hold the IV and the encrypted data
byte[] iv = new byte[aes.BlockSize / 8];
byte[] cipher = new byte[fullCipher.Length - iv.Length];
// Copy the IV and encrypted data from the full cipher byte array
Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, cipher.Length);
// Assign the IV to the AES service
aes.IV = iv;
// Create a decryptor using the AES service
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
// Perform the decryption
byte[] decrypted = decryptor.TransformFinalBlock(cipher, 0, cipher.Length);
// Convert the decrypted byte array back into a string
return Encoding.UTF8.GetString(decrypted);
}
Console.WriteLine("Hello, World!");
string key = "REDACTED_BASE64_STRING";
byte[] secretKey = Convert.FromBase64String(key);
try {
string input = "Hello, world!";
Console.WriteLine("Original text: " + input);
string encryptedText = Encrypt(input, secretKey);
Console.WriteLine("Encrypted text: " + encryptedText);
string decrypted = Decrypt(encryptedText, secretKey);
Console.WriteLine("Decrypted text: " + decrypted);
} catch (Exception e) {
Console.WriteLine(e);
}