gpt4 book ai didi

c# - 使用 StreamWriter 写入 Stream(用于大 Stream 加密)

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:02 25 4
gpt4 key购买 nike

我正在关注 MSDN Example of Rijndael Encryption ,只是我想加密并返回一个流。

以下不起作用。

它没有抛出异常,但是单步执行代码后,返回值没有数据。

        public static Stream EncryptStream(Stream plainStream, byte[] Key, byte[] IV)
{

var encrypted = new MemoryStream()

// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;

// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{

//Write all data to the stream.
swEncrypt.Write(plainStream);
}
msEncrypt.CopyTo(encrypted);
}
}
}
return encrypted;


}

我查看了 documentation for the Stream.Writer class ,以为跟不支持写入Stream有关系。

我注意到有一个“object”类型的参数,所以我假设它会起作用……对吗?如果没有,我该怎么做?

顺便说一句,我将一个 FileStream 传递给它。单步执行代码,plainStream 确实包含数据。

最佳答案

以下是一些用于对流进行加密和解密的示例函数(将算法替换为您喜欢的算法):

public static void Decrypt(Stream input, Stream output, byte[] key, byte[] iv)
{
using (SymmetricAlgorithm algo = SymmetricAlgorithm.Create()) // Creates the default implementation, which is RijndaelManaged.
{
using (CryptoStream stream = new CryptoStream(input, algo.CreateDecryptor(key, iv), CryptoStreamMode.Read))
{
byte[] bytes = new byte[16];
int read;
do
{
read = stream.Read(bytes, 0, bytes.Length);
output.Write(bytes, 0, read);
}
while (read > 0);
}
}
}

public static void Encrypt(Stream input, Stream output, byte[] key, byte[] iv)
{
using (SymmetricAlgorithm algo = SymmetricAlgorithm.Create()) //Creates the default implementation, which is RijndaelManaged.
{
using (CryptoStream stream = new CryptoStream(output, algo.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
byte[] bytes = new byte[16];
int read;
do
{
read = input.Read(bytes, 0, bytes.Length);
stream.Write(bytes, 0, read);
}
while (read > 0);
}
}
}

您可以将它们用于任何输出流。如果你想写入一个大的输出流,你可以直接使用那个输出流(例如 FileStream 或 ASP.NET Response.OutputStream 等),你不应该使用中间的 MemoryStream,它会无意义地消耗内存.

也就是说,如果您真的想使用 MemoryStream,您可以这样做:

MemoryStream output = new MemoryStream();
Encrypt(input, output, key, iv);
output.Position = 0; // rewind the stream, so you can use it from the beginning

关于c# - 使用 StreamWriter 写入 Stream(用于大 Stream 加密),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29025166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com