在C#中,可以使用加密算法来加密和解密byte数组。以下是一个示例代码,演示如何使用AES算法对byte数组进行加密和解密。
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string plaintext = "Hello, world!";
byte[] plainBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] key = Encoding.UTF8.GetBytes("0123456789abcdef");
byte[] iv = Encoding.UTF8.GetBytes("fedcba9876543210");
byte[] encryptedBytes = Encrypt(plainBytes, key, iv);
Console.WriteLine("Encrypted: " + BitConverter.ToString(encryptedBytes).Replace("-", ""));
byte[] decryptedBytes = Decrypt(encryptedBytes, key, iv);
string decryptedText = Encoding.UTF8.GetString(decryptedBytes);
Console.WriteLine("Decrypted: " + decryptedText);
}
static byte[] Encrypt(byte[] plainBytes, byte[] key, byte[] iv)
{
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
}
}
static byte[] Decrypt(byte[] encryptedBytes, byte[] key, byte[] iv)
{
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(encryptedBytes, 0, encryptedBytes.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
}
}
}
在上面的示例中,我们使用AES算法对字符串"Hello, world!"进行加密和解密。首先将明文字符串转换为byte数组,然后使用Encrypt方法对其进行加密,再使用Decrypt方法对加密后的数据进行解密。最后我们将解密后的byte数组转换为字符串输出。