Home >Backend Development >C++ >How Can I Encrypt and Decrypt Data Using AES in C#?

How Can I Encrypt and Decrypt Data Using AES in C#?

DDD
DDDOriginal
2025-01-28 20:26:09889browse

How Can I Encrypt and Decrypt Data Using AES in C#?

Use C# to encrypt AES

Advanced Encryption Standard (AES) is a powerful group password that is widely used for data encryption. In C#, the class provides 128 -bit encryption AES implementation.

RijndaelManaged code example

The following code sample demonstration how to use

class encryption and decryption data:

RijndaelManaged

In this example, the
<code class="language-csharp">using System;
using System.Security.Cryptography;

namespace AES加密
{
    class Program
    {
        static void Main(string[] args)
        {
            // 要加密的原始数据
            string originalText = "这是要加密的数据";

            // 生成密钥和初始化向量 (IV)
            using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
            {
                rijndaelManaged.GenerateKey();
                rijndaelManaged.GenerateIV();

                // 加密数据
                byte[] encryptedText = rijndaelManaged.EncryptStringToBytes(originalText, rijndaelManaged.Key, rijndaelManaged.IV);

                // 解密数据
                string decryptedText = rijndaelManaged.DecryptStringFromBytes(encryptedText, rijndaelManaged.Key, rijndaelManaged.IV);

                // 显示原始数据和解密数据
                Console.WriteLine("原始文本: " + originalText);
                Console.WriteLine("加密文本: " + Convert.ToBase64String(encryptedText));
                Console.WriteLine("解密文本: " + decryptedText);
            }
        }
    }
}</code>
and

methods provide auxiliary functions using specified keys and IV encryption and unlieving string. The statement is added to ensure that the EncryptStringToBytes object is correctly released. DecryptStringFromBytes using Note: RijndaelManaged

Key and IV should be safely generated and stored so that they can be used when decrypting data in the future.

AES can be used for various encryption modes. Code examples use password group links (CBC) mode, but other modes are also available.
  • This Revised Answer Maintains The Original Image and ITS Format While Paraphrasing the Text to Create A PSEUDO-Original Article. Tly Improved by Adding A
  • Statement for Better Resource Management.

The above is the detailed content of How Can I Encrypt and Decrypt Data Using AES in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn