在C#中,可以使用System.Security.Cryptography
命名空間下的類(lèi)來(lái)實(shí)現(xiàn)流的加密解密操作。下面是一個(gè)簡(jiǎn)單的示例代碼:
using System;
using System.IO;
using System.Security.Cryptography;
public class StreamEncryption
{
public static void EncryptStream(Stream inputStream, Stream outputStream, string key)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = new byte[16]; // 16 bytes IV for AES
using (CryptoStream cryptoStream = new CryptoStream(outputStream, aesAlg.CreateEncryptor(), CryptoStreamMode.Write))
{
inputStream.CopyTo(cryptoStream);
}
}
}
public static void DecryptStream(Stream inputStream, Stream outputStream, string key)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = new byte[16]; // 16 bytes IV for AES
using (CryptoStream cryptoStream = new CryptoStream(inputStream, aesAlg.CreateDecryptor(), CryptoStreamMode.Read))
{
cryptoStream.CopyTo(outputStream);
}
}
}
}
在上面的示例中,EncryptStream
方法將輸入流使用AES算法加密后寫(xiě)入輸出流,DecryptStream
方法將輸入流使用AES算法解密后寫(xiě)入輸出流。在使用時(shí),可以將需要加密的數(shù)據(jù)流和加密后的數(shù)據(jù)流傳入這兩個(gè)方法進(jìn)行加密和解密操作。
需要注意的是,對(duì)稱(chēng)加密算法需要提供密鑰(key)和初始化向量(IV),這兩者都需要保密。