aes 256 encrypt string in csharp

To perform AES-256 encryption on a string in C#, you need to follow these steps:

  1. Convert the string into a sequence of bytes using an encoding like UTF-8.
  2. Generate a random 256-bit key using a suitable cryptographic random number generator.
  3. Generate a random 128-bit IV (Initialization Vector) using a suitable cryptographic random number generator.
  4. Create an instance of the AesCryptoServiceProvider class and set its KeySize property to 256 bits.
  5. Set the Key and IV properties of the AesCryptoServiceProvider object to the random key and IV generated in step 2 and 3 respectively.
  6. Create a MemoryStream object to hold the encrypted data.
  7. Use a CryptoStream object to write the encrypted data to the MemoryStream.
  8. Convert the encrypted data to a Base64 string using a suitable encoding.

Here's the code to perform these steps:

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

public static string AesEncrypt(string plainText, string key)
{
    byte[] keyBytes = Encoding.UTF8.GetBytes(key);
    byte[] ivBytes = new byte[16];

    using (RNGCryptoServiceProvider rngCrypto = new RNGCryptoServiceProvider())
    {
        rngCrypto.GetBytes(ivBytes);
    }

    using (AesCryptoServiceProvider aesCrypto = new AesCryptoServiceProvider())
    {
        aesCrypto.KeySize = 256;
        aesCrypto.Key = keyBytes;
        aesCrypto.IV = ivBytes;

        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, aesCrypto.CreateEncryptor(), CryptoStreamMode.Write))
            {
                byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
                csEncrypt.Write(plainBytes, 0, plainBytes.Length);
                csEncrypt.FlushFinalBlock();

                byte[] encryptedBytes = msEncrypt.ToArray();
                byte[] resultBytes = new byte[ivBytes.Length + encryptedBytes.Length];
                Array.Copy(ivBytes, resultBytes, ivBytes.Length);
                Array.Copy(encryptedBytes, 0, resultBytes, ivBytes.Length, encryptedBytes.Length);

                return Convert.ToBase64String(resultBytes);
            }
        }
    }
}
1354 chars
40 lines

You can call this method by passing the plaintext string and the key as parameters. The method returns a Base64 string representation of the encrypted text.

Note: Make sure to keep the randomly generated key and IV secret and safe to be able to decrypt the ciphertext later.

gistlibby LogSnag