Updated program to use streams

This commit is contained in:
n@work 2023-10-06 12:17:34 +01:00
parent 4f78b3ece7
commit 3e543b70e5

View File

@ -1,72 +1,67 @@
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text;
static string Encrypt(string plainText, byte[] secretKey) { /// <summary>
using Aes aes = Aes.Create(); /// Method <c>GetAES</c> creates a custom AES object with the given key
aes.Key = secretKey; /// and IV, and also specifies the cipher mode and padding mode as
/// with the supplier.
// Convert the plain text string into a byte array /// </summary>
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); /// <param name="key">The key to use for the AES object.</param>
/// <param name="iv">The initialization vector to use for the AES object.</param>
// Create an encryptor using the AES service and its initialization vector (IV) static Aes CreateAES(byte[] key, byte[] iv) {
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); Aes aes = Aes.Create(); // Create a new instance of Aes
aes.KeySize = key.Length * 8; // Key size is set to the length of the input key multiplied by 8
// Perform the encryption aes.Key = key; // The Key and IV values are set from the parameters
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; aes.IV = iv;
aes.Mode = CipherMode.CBC; // Cipher mode is set to CBC (Cipher Block Chaining) mode
// Create a decryptor using the AES service aes.Padding = PaddingMode.PKCS7; // Padding mode is set to PKCS7 (Public Key Cryptography Standard #7) padding
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); return aes;
// 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);
} }
/// <summary>
/// Method <c>Encrypt</c> encrypts the given plain text using the provided AES object.
/// </summary>
/// <param name="plainText">The plain text to encrypt.</param>
/// <param name="aes">The AES object to use for encryption.</param>
/// <returns>The encrypted text as a base64 string.</returns>
static string Encrypt(string plainText, Aes aes) {
using MemoryStream memoryStream = new(); // Creates a new memory stream for writing data
using CryptoStream cryptoStream = new(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write); // Creates a new CryptoStream using the given Aes object and the memory stream for writing data
using StreamWriter streamWriter = new(cryptoStream); // Creates a new StreamWriter using the above CryptoStream
streamWriter.Write(plainText); // Writes the plain text to the StreamWriter
cryptoStream.FlushFinalBlock(); // Writes the final block of data to the CryptoStream and closes the stream
string output = Convert.ToBase64String(memoryStream.ToArray()); // Converts the contents of the memory stream to a byte array and returns the base64-encoded string representation of the array
return output; // Returns the encrypted output as a base64 string
}
Console.WriteLine("Hello, World!"); /// <summary>
/// Method <c>Decrypt</c> decrypts the given encrypted text using the provided AES object.
/// </summary>
/// <param name="encryptedText">The encrypted text to decrypt, as a Base64 string.</param>
/// <param name="aes">The AES object to use for decryption.</param>
/// <returns>The decrypted string, in plain-text</returns>
static string Decrypt(string encryptedText, Aes aes) {
using MemoryStream memoryStream = new(Convert.FromBase64String(encryptedText)); // Creates a new memory stream using the given encrypted text, converted from a base64 string to a byte array
using CryptoStream cryptoStream = new(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read); // Creates a new CryptoStream using the given AES object and the memory stream for reading data
using StreamReader streamReader = new(cryptoStream); // Creates a new StreamReader using the above CryptoStream
string output = streamReader.ReadToEnd(); // Reads the entire stream and returns the contents as a string
return output; // Returns the decrypted output as a string
}
string key = "REDACTED_BASE64_STRING"; byte[] key = Convert.FromBase64String("REDCATED");
byte[] secretKey = Convert.FromBase64String(key); byte[] iv = Convert.FromBase64String("REDACTED");
using Aes aes = CreateAES(key, iv);
string plainText = "Hello, AES-CBC with PKCS7 padding!";
string encrypted = Encrypt(plainText, aes);
Console.WriteLine($"Encrypted text: '{encrypted}' (from '{plainText}')");
string decrypted = Decrypt(encrypted, aes);
Console.WriteLine($"Decrypted text: '{decrypted}' (from '{encrypted}')");
Console.WriteLine();
string secureText = "REDACTED";
try { try {
string input = "Hello, world!"; string decrypted2 = Decrypt(secureText, aes);
Console.WriteLine("Original text: " + input); Console.WriteLine($"Previously encrypted decrypted text: '{decrypted2}' (from '{secureText}')");
} catch (Exception ex) {
string encryptedText = Encrypt(input, secretKey); Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine("Encrypted text: " + encryptedText);
string decrypted = Decrypt(encryptedText, secretKey);
Console.WriteLine("Decrypted text: " + decrypted);
} catch (Exception e) {
Console.WriteLine(e);
} }