0

大多数示例使用 MemoryStream 和 CryptoStream 来使用 RijndaelManaged 进行加密/解密,所以我尽可能地简化它,并最终使用以下函数来解密缓冲区。

RijndaelManaged csp; //is initialized wih CBC/256bit key and padding
ICryptoTransform decryptor = csp.CreateDecryptor(csp.Key, csp.IV);

public void Decrypt(ref byte[] message, ref int len)
{
    using (MemoryStream msDecrypt = new MemoryStream(message.AsSpan().Slice(0, len).ToArray())) //the buffer is larger than the actual data so we slice it to the actual size
    {
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        {
            len = csDecrypt.Read(message, 0, message.Length); //we write the encrypted data back into the buffer and set the length to the new size
        }
    }
}

它正在工作,但是我的应用程序现在正在处理很多 ReadOnlySpan,并且必须使用“ToArray()”分配一个新缓冲区才能加密/解密它们,这感觉很奇怪,因为大多数 Streams 现在都能够使用 Span in他们的 Read 和 Write 方法。

public void Decrypt(ref Span<byte> output, ref ReadOnlySpan<byte> input)
{
    using (MemoryStream msDecrypt = new MemoryStream(input)) //This is not possible
    {
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        {
            csDecrypt.Read(output);
        }
    }
}

是否有与上述类似的方法(即使它需要更多步骤)允许在不分配额外缓冲区的情况下使用 CryptoStream?

4

0 回答 0