"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to implement AES encryption in C#?

How to implement AES encryption in C#?

Posted on 2025-03-13
Browse:633

How Can I Implement AES Encryption in C#?

AES Encryption in C#: Practical Guide

]

Introduction

In the field of data security, the Advanced Encryption Standard (AES) is highly regarded as an efficient symmetric encryption algorithm. AES uses its powerful 128-bit, 192-bit or 256-bit keys to ensure your sensitive information is protected from unauthorized access.

Sample implementation

If you want to take advantage of the power of AES in your C# application, consider the following code example:

using System;
using System.IO;
using System.Security.Cryptography;

namespace Aes加密示例
{
    class Program
    {
        static void Main()
        {
            try
            {
                // 原始数据
                string original = "机密信息";

                // 密钥和初始化向量 (IV)
                byte[] key = { ... };
                byte[] iv = { ... };

                // 加密数据
                byte[] encrypted = Encrypt(original, key, iv);

                // 解密数据
                string decrypted = Decrypt(encrypted, key, iv);

                // 验证解密
                if (original == decrypted)
                    Console.WriteLine("解密成功。");
                else
                    Console.WriteLine("解密失败。");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误:{ex.Message}");
            }
        }

        // 加密方法
        public static byte[] Encrypt(string plainText, byte[] key, byte[] iv)
        {
            using (AesManaged aes = new AesManaged())
            {
                aes.Key = key;
                aes.IV = iv;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(cs))
                        {
                            sw.Write(plainText);
                        }

                        return ms.ToArray();
                    }
                }
            }
        }

        // 解密方法
        public static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
        {
            using (AesManaged aes = new AesManaged())
            {
                aes.Key = key;
                aes.IV = iv;
                using (MemoryStream ms = new MemoryStream(cipherText))
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            return sr.ReadToEnd();
                        }
                    }
                }
            }
        }
    }
}

in conclusion

This code sample provides a clean and practical way to integrate AES encryption in your C# project. With its built-in encryption provider, RijndaelManaged, AES provides unparalleled data protection to ensure your sensitive information is protected from snooping.

The changes made include:

  • Replacing "Confidential information" with "Confidential Information in Chinese) to avoid revealing sensitive data in the example.
  • Minor wording adjustments for improved flow and clarity, maintaining the original meaning.
  • The title and section headings are slightly altered to sound more natural in the context of a Chinese-language article, while keeping the original meaning.
  • The image caption is modified to reflect the change in the main language of the article.

The image remains in its original format and location. Remember to replace the ... in the key and iv variables with actual key and IV values ​​for a functional implementation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3