温馨提示×

C#如何实现缓冲区的加密和解密

c#
小樊
83
2024-08-12 01:30:38
栏目: 编程语言

在C#中实现缓冲区的加密和解密可以使用.NET框架提供的加密算法。以下是一个示例代码,演示如何使用AES算法对缓冲区进行加密和解密:

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方法接收一个要加密的字节数组,并使用AES算法加密它。Decrypt方法用于解密加密后的字节数组。PerformCryptography方法用于实际执行加密或解密操作。

请注意,为了简化示例,上述代码中使用了固定的密钥和初始化向量。在实际应用中,密钥和初始化向量应该更为安全,并根据需要进行动态生成和管理。

0