1

Most of the exemples use MemoryStream with CryptoStream to encrypt/decrypt with RijndaelManaged so I simplified it as much as I could and ended up with the following function to decrypt a buffer.

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
        }
    }
}

It is working, but my application is now dealing with a lot of ReadOnlySpan and it feels weird to have to allocate a new buffer with "ToArray()" to be able to encrypt/decrypt them as most Streams are now capable of using Span in their Read and Write methods.

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);
        }
    }
}

Is there a way similar to the above(even if it requires more steps) that allow the use of CryptoStream without allocating an additional buffer?

Lizi
  • 153
  • 1
  • 9
  • You *could* use the Span in a `fixed` statement and then pass the pointer and the length to `UnmanagedMemoryStream` – pinkfloydx33 May 15 '20 at 22:06
  • @pinkfloydx33 thank you I will keep this solution in mind if I can't find any that don't use /unsafe as it would require some tweaks of the production environment. – Lizi May 15 '20 at 22:31

0 Answers0