Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding command line OpenSSL DGST Sha256 command

I have the command openssl dgst -sha256 -binary _your_file_path_ | openssl enc -base64 I use in terminal to get an output for a jar file that matches what AWS Lambda uses to hash.

I want to program that in Java, but I am having trouble understanding exactly what is going on in that line, so that I can go through each step in my code. Obviously, there is mode than just hashing in SHA256, because when I do that the output does not match.

Could someone help explain the steps that line is completing in a simple way for me?

like image 779
Starlord Avatar asked Jun 18 '26 03:06

Starlord


1 Answers

You need to break the command down to understand what is going on.

  1. The first part of the command:
    • openssl dgst -sha256 -binary <file> gives you a SHA256 binary checksum for the file.
  2. The second part of the command:
    • openssl enc -base64 encodes the SHA256 binary checksum to Base64.

So to replicate in Java, you just need to carry out those same steps:

  1. Calculate a SHA256 binary checksum.
  2. Base64 encode the SHA256 binary checksum.

Without you posting the command you used to try and get a SHA256 checksum separately to the command you did post, I'm guessing the reason you were probably getting a different hash is because by default a checksum seems to output in hexadecimal.

See my example below and how the results are completely different.

# Hexadecimal
$ openssl dgst -sha256 data.csv
SHA256(data.csv)= 114811b0b8998cb9853a5379598021410feddf69bb2ee7b7145d052a7e9b5d45

# Binary (note the usage of the -binary flag)
$ openssl dgst -sha256 -binary data.csv
H:SyY!Ai.]*~]E

If you then Base64 encode the hexadecimal checksum above, and the binary one, you'll also get two completely different results, as you can see below.

# Hexadecimal
$ printf 114811b0b8998cb9853a5379598021410feddf69bb2ee7b7145d052a7e9b5d45 | openssl enc -base64
MTE0ODExYjBiODk5OGNiOTg1M2E1Mzc5NTk4MDIxNDEwZmVkZGY2OWJiMmVlN2I3
MTQ1ZDA1MmE3ZTliNWQ0NQ==

# Binary
$ printf 'H:SyY!Ai.]*~]E' | openssl enc -base64
SDpTeVkhQWkuXSp+XUU=