Search code examples
c#sdksha2567ziplzma

Hashing decompressed and compressed files with 7zip sdk - c#


I am using the 7z SDK to compress and decompress files. I want to read the file before compressing it, generate a sha256 hash, write on the file and compress it.

When decompressing, I will read the hash, store it in a variable, decompress the file and get a new hash to compare with the hash stored in the variable to check the integrity of the file.

When compressing the file I included this block:

            //Write the hash size from the original file
            int HashCodeSize = Hash.generateSHA256Hash(input).Length;
            byte[] hashSize = BitConverter.GetBytes(HashCodeSize);
            output.Write(hashSize, 0, hashSize.Length);

            //Write the hash from the original file
            byte[] fileHashCode = new byte[8];
            fileHashCode = Hash.generateSHA256Hash(input);
            output.Write(fileHashCode, 0, fileHashCode.Length);

When decompressing the file I do this:

            //read the hash size from the original file
            byte[] hashSize = new byte[4];
            input.Read(hashSize, 0, 4);
            int sizeOfHash = BitConverter.ToInt16(hashSize, 0);

            //Read Hash
            byte[] fileHash = new byte[sizeOfHash];
            input.Read(fileHash, 0, 8);

When I include those two blocks, I get an *unhandled exception from the SDK, without them blocks the program works perfectly.

That is how I am generating the Hash:

public static byte[] generateSHA256Hash(Stream fileSource)
{
    SHA256 fileHashed = SHA256Managed.Create();
    return fileHashed.ComputeHash(fileSource);
}

Does anyone know what I am doing wrong?

unhandled execption


Solution

  • Moving the pointer to the begining of the file before writing it solved my problem:

     input.Seek(0, SeekOrigin.Begin);