在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數組轉換為字符串輸出。