schmiddl
schmiddl

Reputation: 95

How to calculate sha1 base64 encoded in windows batch?

I am trying to get a base64 encoded sha1 hash in a windows batch file. The first thing I tried was with perl:

perl -M"Digest::SHA1 qw(sha1_base64)" -e "open(F,shift) or die; binmode F; print sha1_base64(<F>), qq(=\n)" "test.mxf"

This works great, but only for small files. With big files it says "Out of memory".

Then I downloaded an openssl version for windows and tried this:

"C:\openssl.exe" dgst -sha1 -binary -out "hash_sha1.txt" "C:\test.mxf"
set /p hash_sha1=<"hash_sha1.txt"
del "hash_sha1.txt"
echo !hash_sha1!

echo -n '!hash_sha1!' | "C:\openssl.exe" enc -base64

But the output of the openssl method is different from the Perl output and I know that the Perl method produces the correct output. What do I have to change?

Upvotes: 1

Views: 2285

Answers (2)

Borodin
Borodin

Reputation: 126742

If you create a Digest::SHA1 object, you can use the add method to calculate the hash incrementally

There is also no need to explicitly open files passed as command-line parameters. They are opened automatically using the built-in file handle ARGV, and can be read with the empoty diamond operator <>

perl -Mopen=IN,:raw -MDigest::SHA1 -e"$d=Digest::SHA1->new; $d->add($_) while <>; print $d->b64digest, qq{=\n}" 5GB.bin

This command line was quite happy to generate the SHA1 hash of a 5GB file, but if you are unlucky enough to have a very big file that contains no linefeeds then you will have to set a read block size with something like

local $/ = \(1024*1024)

Upvotes: 2

woxxom
woxxom

Reputation: 73686

  • There's no -n parameter of echo so -n AND single quotes are part of the output.
  • The intermediate files and variables aren't needed, use piping.

The entire code:

openssl dgst -sha1 -binary "C:\test.mxf" | openssl enc -base64

Upvotes: 5

Related Questions