Calculating Binary Hashes using TJwFileStreamEx
Why should I use TJwFileStreamEx instead of any other common stream class from the VCL?
Well this question is quite easily answered.
The first thing is that TJwFileStreamEx is based on Memory Mapped Files (MMF). MMF might be the fastest way to access files on your hard disk. Another good reason for using TJwFileStreamEx is its Memory property which is well known from the VCL TMemoryStream class. This property will reduce the effort remarkably.
First you have to include following units to your project:
The signature of our hashing-function looks like this:
The first parameter is used to specify the Algorithm which is used to hash the file data. The second parameter defines the path to the file which hash you want to compute.
So what do we need to calculate the hash of a file? All we need is an instance of TJwFileStreamEx to open the file and an instance of TJwHash to calculate the hash:
This is the basic framework of our function. To calculate the hash of the file we need 2 methods:
HashData tells our instance of TJwHash which data is to be hashed and which size this data has. RetrieveHash calculates the Hash and retrieves a pointer to the hash data.
Finally we have to free the Buffer using the class method
Now our function looks like this:
At last we need to convert the binary hash into a hex-string:
Now we’re done and finally our function looks like this:
for i:= 1 to HashSize do
Result := Result + IntToHex(PByte(HashData)^,2);
How do I use this function?
OK, but what is the advantage of TJwFileStreamEx over other Streams?
Well, you don’t have to load the file into a TMemoryStream and thus the file will not be loaded completely into memory. Furthermore this solution is much faster than a solution using TMemoryStream and similar…
Download the source and binaries of this example (260kiB). This includes the new and necessary JWSCL source files. However you need to download the whole package separately.