SoFunction
Updated on 2025-03-04

Example of AES encryption and decryption using C#

1. Introduction to AES Encryption

AES (Advanced Encryption Standard) is a symmetric encryption algorithm that means encryption and decryption use the same key. AES supports different key lengths such as 128 bits, 192 bits, and 256 bits. For simplicity, this article will use a 128-bit key (i.e., 16-byte) for encryption.

2. AES encryption and decryption in C#

In C#, namespaces provide built-in AES encryption support. Through the Aes class, we can easily implement encryption and decryption operations. Here is a complete sample code showing how to perform AES encryption and decryption in C#.

    class Program
    {
        private static string key = "1234567890123456"; // 16-byte key, AES-128        private static string iv = "1234567890123456";  // 16-byte IV (initialization vector) 
        // Encryption function        public static string Encrypt(string plainText)
        {
            using (Aes aesAlg = ()) // Create an AES encryption instance            {
                 = Encoding.(key);  // Set the key                 = Encoding.(iv);    // Set initialization vector 
                ICryptoTransform encryptor = (, ); // Create an encryptor 
                using (MemoryStream msEncrypt = new MemoryStream())  // Used to store encrypted data                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, ))  // Create an encrypted data stream                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))  // Write to the encrypted stream                        {
                            (plainText);  // Write plain text data                        }
                    }
                    // Return the encrypted data and convert it to Base64 string                    return Convert.ToBase64String(());
                }
            }
        }
 
        // Decrypt the function        public static string Decrypt(string cipherText)
        {
            using (Aes aesAlg = ()) // Create an AES instance            {
                 = Encoding.(key);  // Set the key                 = Encoding.(iv);    // Set initialization vector 
                ICryptoTransform decryptor = (, );  // Create a decryptor 
                using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))  // Convert Base64 string to byte array and read                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, ))  // Create a decrypted data stream                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))  // Read data from the decrypted stream                        {
                            return ();  // Return to the decrypted plain text                        }
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            string originalText = "Hello, AES Encryption!";  // Original plain text            ("Original Text: " + originalText);  // Output original text 
            string encryptedText = Encrypt(originalText);  // Encryption            ("Encrypted Text: " + encryptedText);  // Output encrypted text 
            string decryptedText = Decrypt(encryptedText);  // Decrypt            ("Decrypted Text: " + decryptedText);  // Output decrypted text 
            ();
        }
    }

3. Detailed code explanation

  1. Key and initialization vector (IV)

    • In AES encryption, the key length and the length of the initialization vector (IV) are very important. Here is a 16-byte key (128-bit) and a 16-byte IV. This is the standard setting required for AES-128 encryption.
  2. Encryption process

    • use()Create an AES instance.
    • Setting the key (Key) and initialization vector (IV)。
    • useCreateEncryptorCreate an encryptor, and then passCryptoStreamandMemoryStreamImplement encryption of data streams.
    • The encrypted byte stream is eventually converted into a Base64 string for easy storage or transmission in text.
  3. Decryption process

    • The decryption process is the opposite of the encryption process. We use the same key and IV, throughCreateDecryptorDecrypt the data stream and finally restore the original text.

4. Sample output

Suppose we encrypt and decrypt a piece of text"Hello, AES Encryption!", the output will look like this:

Original Text: Hello, AES Encryption!
Encrypted Text: P5/fGFh/sUsYOGYOg7wDIA==
Decrypted Text: Hello, AES Encryption!

As you can see, the original text is successfully encrypted and converted into a Base64-encoded string, and then decrypted back to the original plaintext.

5. Safety precautions

In practical applications, the generation of keys and initialization vectors should be more complex and random to improve encryption security. Avoid using fixed keys and IVs, especially in production environments.

For example, you can useRNGCryptoServiceProviderto generate a random key and IV instead of manually specifying them. This enhances the strength of encryption and ensures unique security for each encryption.

6. Conclusion

With the above examples, we learned how to implement AES encryption and decryption using C#. AES is an efficient and secure symmetric encryption algorithm, widely used in various data protection and information security scenarios. Mastering its implementation can help us protect sensitive data during development and ensure the security of our applications.

This is the end of this article about using C# to implement AES encryption and decryption. For more related C# AES encryption and decryption content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!