龙空技术网

C# AES算法进行加密和解密 简单例子

凡人兔子张 131

前言:

而今大家对“aes加密算法”大体比较注意,看官们都需要剖析一些“aes加密算法”的相关知识。那么小编同时在网上搜集了一些有关“aes加密算法””的相关内容,希望小伙伴们能喜欢,兄弟们快快来学习一下吧!

C#中可以使用AES算法进行加密和解密。

以下是一个简单的示例代码,演示如何使用AES算法进行加密和解密:

using System;using System.Security.Cryptography;using System.Text;public class AesEncryptionExample{    public static byte[] Encrypt(string plainText, byte[] key, byte[] iv)    {        using (Aes aes = Aes.Create())        {            aes.Key = key;            aes.IV = iv;            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);            using (MemoryStream memoryStream = new MemoryStream())            {                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))                {                    byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);                    cryptoStream.Write(plainBytes, 0, plainBytes.Length);                    cryptoStream.FlushFinalBlock();                    return memoryStream.ToArray();                }            }        }    }    public static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)    {        using (Aes aes = Aes.Create())        {            aes.Key = key;            aes.IV = iv;            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);            using (MemoryStream memoryStream = new MemoryStream(cipherText))            {                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))                {                    byte[] plainBytes = new byte[cipherText.Length];                    int decryptedByteCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);                    return Encoding.UTF8.GetString(plainBytes, 0, decryptedByteCount);                }            }        }    }    public static void Main()    {        string plainText = "Hello, world!";        byte[] key = new byte[32]; // 256-bit key        byte[] iv = new byte[16]; // 128-bit IV        // Generate random key and IV        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())        {            rng.GetBytes(key);            rng.GetBytes(iv);        }        byte[] cipherText = Encrypt(plainText, key, iv);        string decryptedText = Decrypt(cipherText, key, iv);        Console.WriteLine("Plain Text: " + plainText);        Console.WriteLine("Cipher Text: " + Convert.ToBase64String(cipherText));        Console.WriteLine("Decrypted Text: " + decryptedText);    }}

这个示例使用了AES算法和256位的密钥来加密和解密字符串。

您可以根据需要调整密钥和IV的长度。

请注意,密钥和IV应该是随机生成的,并且在加密和解密过程中需要保持一致。

希望这个示例对您有帮助!

标签: #aes加密算法