implement aes decrypt in csharp

Here is an example of how to implement AES decryption in C#:

main.cs
using System;
using System.IO;
using System.Security.Cryptography;

public static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
{
    // Check arguments.
    if (cipherText == null || cipherText.Length <= 0)
    {
        throw new ArgumentNullException(nameof(cipherText));
    }
    
    if (key == null || key.Length <= 0)
    {
        throw new ArgumentNullException(nameof(key));
    }
    
    if (iv == null || iv.Length <= 0)
    {
        throw new ArgumentNullException(nameof(iv));
    }
    
    string plaintext = null;
    
    // Create an AES object with the specified key and IV.
    using (Aes aesAlg = Aes.Create())
    {
        aesAlg.Key = key;
        aesAlg.IV = iv;

        // Create a decrytor to perform the stream transform.
        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

        // Create the streams used for decryption.
        using (MemoryStream msDecrypt = new MemoryStream(cipherText))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {
                    // Read the decrypted bytes from the decrypting stream 
                    // and place them in a string.
                    plaintext = srDecrypt.ReadToEnd();
                }
            }
        }
    }

    return plaintext;
}
1468 chars
51 lines

To use this method, you would need to provide the following parameters:

  • cipherText: The encrypted text to decrypt.
  • key: The secret key used for encryption.
  • iv: The initialization vector used for encryption.

Example usage:

main.cs
string encryptedText = "...";
byte[] key = new byte[] { ... };
byte[] iv = new byte[] { ... };

string decryptedText = DecryptStringFromBytes(Convert.FromBase64String(encryptedText), key, iv);
193 chars
6 lines

gistlibby LogSnag