C # DataReader issue when used with transformed stream .AsInputStream ()

I need to do various reads in a stream for the decryption process. (for the WinRT project) For one, I would like to do ReadByte () to get the first byte of the stream. There - after I would like to read a few bytes in the array, and then read the rest of the bytes into the buffer.

I open a DataReader for the passed IInputStream object. This, in turn, was created from the System.IO.Stream object using the .AsInputStream () method. When I look at a DataReader object during debugging, I see that UnconsumedBufferLength is 0, and I cannot execute ReadByte () or ReadBytes () to not get the exception "Operation attempting to access data out of range".

Why does the DataReader seem empty? I had problems with the AsInputStream () method, which previously did not return the actual IInputStream. How can I end up opening a DataReader object of a System.IO.Stream object.

Code where DataReader is assigned:

private Stream DecryptStream(IInputStream streamToDecrypt, byte[] key)
    {
        try
        {
            var dataReader = new DataReader(streamToDecrypt);

            int ivLength = dataReader.ReadByte();  //Throws exception (UnconsumedBufferLength = 0 remember)

            byte[] iv = new byte[ivLength];
            dataReader.ReadBytes(iv);   //Throws exception (UnconsumedBufferLength = 0 remember)


            IBuffer toDecryptBuffer = new Windows.Storage.Streams.Buffer(dataReader.UnconsumedBufferLength);
            toDecryptBuffer = dataReader.ReadBuffer(dataReader.UnconsumedBufferLength);   //Works, but only because toDecryptBuffer is of length 0. which is still useless. 

Code calling the above method:

Stream plainStream = DecryptStream(streamToDecrypt.AsInputStream(),key);

Update: the code that created the thread. Here the first thread is created from the System.IO.Compression.ZipArchive object. This is then passed to the intermediate decryption function as "streamToDecrypt"

ZipArchiveEntry metaEntry = archive.Entries.Where(x => x.FullName == "myFullNameHere").FirstOrDefault();
Stream returnStream = metaEntry.Open();
+4
source share
1 answer

You need to call datareader.LoadAsync (size) to load the file into the buffer before reading it.

- :

private async Task<Stream> DecryptStream(IInputStream streamToDecrypt, byte[] key, int uncompressedSize)
{
    try
    {
        var dataReader = new DataReader(streamToDecrypt);
        await datareader.LoadAsync(uncompressedSize);

        int ivLength = dataReader.ReadByte();  //Throws exception (UnconsumedBufferLength = 0 remember)

        byte[] iv = new byte[ivLength];
        dataReader.ReadBytes(iv);   //Throws exception (UnconsumedBufferLength = 0 remember)

, , ZipArchiveEntry:

await DecryptStream(streamToDecrypt.AsInputStream(),key, streamToDecrypt.Length);
+3

Source: https://habr.com/ru/post/1546302/


All Articles