How to implement a C# AES-256 encrypt and decrypt function?

jing tian 20 Reputation points
2023-05-25T12:31:50.9+00:00

I have a C# function like this, But if the keyBytes length is 32, then the TransformFinalBlock() will throw a error: The padding is invalid and cannot be removed. I wont to decrypt a secret string form my customer,but always error.

public static byte[] AesDecypt(byte[] contents, byte[] keyBytes)
        {
            try
            {
                RijndaelManaged rm = new RijndaelManaged
                {
                    Key = keyBytes,
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };

                ICryptoTransform cTransform = rm.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(contents, 0, contents.Length);

                return resultArray;
            }
            catch
            {
                return contents;
            }
        }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,229 questions
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 31,516 Reputation points Microsoft Vendor
    2023-05-26T08:31:49.31+00:00

    Hi @jing tian , Welcome to Microsoft Q&A.

    A similar error will appear if you enter the wrong number of digits.

    You can try the example below.

    using System;
    using System.Security.Cryptography;
    using System.Text;
    
    namespace xxx
    {
       public class AesEncryption
        {
            public static byte[] Encrypt(string plaintext, byte[] key, byte[] iv)
            {
                using (Aes aesAlg = Aes.Create())
                {
                    aesAlg.Key = key;
                    aesAlg.IV = iv;
                   ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                   byte[] encryptedBytes;
                   using (var msEncrypt = new System.IO.MemoryStream())
                    {
                       using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        {
                            byte[] plainBytes = Encoding.UTF8.GetBytes(plaintext);
                            csEncrypt.Write(plainBytes, 0, plainBytes.Length);
                        }
                       encryptedBytes = msEncrypt.ToArray();
                    }
                    return encryptedBytes;
                }
            }
           public static string Decrypt(byte[] ciphertext, byte[] key, byte[] iv)
            {
                using (Aes aesAlg = Aes.Create())
                {
                    aesAlg.Key = key;
                    aesAlg.IV = iv;
                   ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                   byte[] decryptedBytes;
                   using (var msDecrypt = new System.IO.MemoryStream(ciphertext))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (var msPlain = new System.IO.MemoryStream())
                            {
                                csDecrypt.CopyTo(msPlain);
                                decryptedBytes = msPlain.ToArray();
                            }
                        }
                    }
                   return Encoding.UTF8.GetString(decryptedBytes);
                }
            }
        }
       internal class Program
        {
            static void Main(string[] args)
            {
                string plaintext = "Hello, World!";
                Console.WriteLine(plaintext);
               // Generate a random key and IV
                byte[] key = new byte[32]; // 256-bit key
                byte[] iv = new byte[16]; // 128-bit IV
                using (var rng = new RNGCryptoServiceProvider())
                {
                    rng.GetBytes(key);
                    rng.GetBytes(iv);
                }
               // Encrypt
                byte[] ciphertext = AesEncryption.Encrypt(plaintext, key, iv);
                string encryptedText = Convert.ToBase64String(ciphertext);
                Console.WriteLine("Encrypted Text: " + encryptedText);
               // Decrypt
                byte[] bytes = Convert.FromBase64String(encryptedText);
                string decryptedText = AesEncryption.Decrypt(bytes, key, iv);
                Console.WriteLine("Decrypted Text: " + decryptedText);
                //point
                Console.ReadLine();
            }
        }
    
    }
    
    

    enter image description here

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Mohammad 0 Reputation points
    2023-12-06T10:21:40.22+00:00

    Hi everyone,

    I've code with
    byte[] iv = new byte[32];

    Is this right?

    If yes, describe me how. Thanks

    0 comments No comments