Compute base64 encoded hash from a given hash?

2019-02-20 19:36发布

I created a file and input some random string into it.

touch tesseract && echo 'TestTestTestTestTest' > tesseract

Now if I use openssl to compute base64 hash [sha256], I run this:

cat tesseract | openssl dgst -sha256 | openssl base64 -A

which returns me

KHN0ZGluKT0gMzJjYjA1MTgzNDNhZmY2N2FlMmY5YzUwNDcwNGRiNGE5Njc5MzIyZWVlNTBmMjBiNTMzNjZlYTBiMDY2MWNlZgo=

Now I process this hash stepwise, as,

cat tesseract | openssl dgst -sha256 > partialHash

which gives me

(stdin)= 32cb0518343aff67ae2f9c504704db4a9679322eee50f20b53366ea0b0661cef

Let this hash be X. Then I do this,

echo '32cb0518343aff67ae2f9c504704db4a9679322eee50f20b53366ea0b0661cef' > partialHash
cat partialHash | openssl base64 -A

I get a different result. Why is that?

My reason for asking is because I use a binary, hashdeep which gives me hashes in form of 32cb0518343aff67ae2f9c504704db4a9679322eee50f20b53366ea0b0661cef and I wish to convert them to base64 encoded format as hashdeep is not capable of producing a base64 output. So I pipe the intermediate hash to openssl base64 -A, but obtain a different result.

What am I missing? How can I convert the non-encoded hash X [which is 32cb0518343aff67ae2f9c504704db4a9679322eee50f20b53366ea0b0661cef] to proper base64 encoded format?

For simplicity purpose, we can assume that X is present in a file,
created using echo '32cb0518343aff67ae2f9c504704db4a9679322eee50f20b53366ea0b0661cef' > file

1条回答
smile是对你的礼貌
2楼-- · 2019-02-20 20:10

You're not base-64 encoding the hash. You're base64-encoding the string

(stdin)= 32cb0518343aff67ae2f9c504704db4a9679322eee50f20b53366ea0b0661cef

(followed by a newline). Note the (stdin)= at the beginning. That's part of the string. That's going to have a different value than the base64 encoding of the string 32cb0518343aff67ae2f9c504704db4a9679322eee50f20b53366ea0b0661cef (followed by a newline).

If your goal is to get binary hashes (rather than their string encodings), then use the -binary option to openssl dgst.

I'm not familiar with hashdeep, but when you say "non-encoded hash," that's not what it's generating. It's generating a hex-encoded hash. By the looks of it you're really looking for a hex-to-base64 converter. You can do that along these lines:

echo '32cb0518343aff67ae2f9c504704db4a9679322eee50f20b53366ea0b0661cef' | xxd -r -p  | base64

xxd -r -p converts a hex-encoded string into raw data.

(If you're using openssl dgst, just make sure that you're using options that don't inject (stdin)= on the front. My version of openssl doesn't do this, so I'm not certain what flag you'll need.)

查看更多
登录 后发表回答