C#如何實(shí)現(xiàn)緩沖區(qū)的加密和解密

c#
小樊
83
2024-08-12 01:30:38

在C#中實(shí)現(xiàn)緩沖區(qū)的加密和解密可以使用.NET框架提供的加密算法。以下是一個(gè)示例代碼,演示如何使用AES算法對(duì)緩沖區(qū)進(jìn)行加密和解密:

using System;
using System.Security.Cryptography;
using System.Text;

public class EncryptionHelper
{
    private const string key = "1234567890123456";
    private const string iv = "1234567890123456";

    public static byte[] Encrypt(byte[] buffer)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = Encoding.UTF8.GetBytes(iv);

            using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
            {
                return PerformCryptography(buffer, encryptor);
            }
        }
    }

    public static byte[] Decrypt(byte[] buffer)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = Encoding.UTF8.GetBytes(iv);

            using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
            {
                return PerformCryptography(buffer, decryptor);
            }
        }
    }

    private static byte[] PerformCryptography(byte[] buffer, ICryptoTransform transform)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
            {
                cryptoStream.Write(buffer, 0, buffer.Length);
            }

            return memoryStream.ToArray();
        }
    }
}

在上面的代碼中,Encrypt方法接收一個(gè)要加密的字節(jié)數(shù)組,并使用AES算法加密它。Decrypt方法用于解密加密后的字節(jié)數(shù)組。PerformCryptography方法用于實(shí)際執(zhí)行加密或解密操作。

請(qǐng)注意,為了簡(jiǎn)化示例,上述代碼中使用了固定的密鑰和初始化向量。在實(shí)際應(yīng)用中,密鑰和初始化向量應(yīng)該更為安全,并根據(jù)需要進(jìn)行動(dòng)態(tài)生成和管理。

0