Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SHA256 hashes finish with " = "?

I've made a Webservice which returns a security Token after a successful authentification.

However when debugging I noticed that every hash the webservice returned finishes with "=" such as:

"tINH0JxmryvB6pRkEii1iBYP7FRedDqIEs0Ppbw83oc="
"INv7q72C1HvIixY1qmt5tNASFBEc0PnXRSb780Y5aeI="
"QkM8Kog8TtCczysDmKu6ZOjwwYlcR2biiUzxkb3uBio="
"6eNuCU6RBkwKMmVV6Mhm0Q0ehJ8Qo5SqcGm3LIl62uQ="
"dAPKN8aHl5tgKpmx9vNoYvXfAdF+76G4S+L+ep+TzU="
"O5qQNLEjmmgCIB0TOsNOPCHiquq8ALbHHLcWvWhMuI="
"N9ERYp+i7yhEblAjaKaS3qf9uvMja0odC7ERYllHCI="
"wsBTpxyNLVLbJEbMttFdSfOwv6W9rXba4GGodVVxgo="
"sr+nF83THUjYcjzRVQbnDFUQVTkuZOZYe3D3bmF1D8="
"9EosvgyYOG5a136S54HVmmebwiBJJ8a3qGVWD878j5k="
"8ORZmAXZ4dlWeaMOsyxAFphwKh9SeimwBzf8eYqTis="
"gVepn2Up5rjVplJUvDHtgIeaBL+X6TPzm2j9O2JTDFI="

Why such a behavior ?

like image 264
Fortune Avatar asked Jun 05 '15 12:06

Fortune


2 Answers

This is because you don't see the raw bytes of the hash but rather the Base64 encoding.

Base64-encoding converts a block of 3 bytes to a block of four characters. This works well if the number of bytes is divisible by 3. If it is not, then you use a padding-character so the number of resulting characters is still divisible by 4.

So:

(no of bytes)%3 = 0  => no padding needed
(no of bytes)%3 = 1  => pad with ==
(no of bytes)%3 = 2  => pad with =

A SHA256-hash is 256 bit, that's 32 bytes. So you will get 40 characters for the first 30 bytes, 3 characters for the last 2 bytes and the padding will always be one =.

like image 126
piet.t Avatar answered Oct 05 '22 10:10

piet.t


These strings are encoded using base64, = characters are used as paddings, to make the last block of a base64 string contains four characters.


The following Ruby code could be used to get base64 decoded string:

require 'base64'

s = "tINH0JxmryvB6pRkEii1iBYP7FRedDqIEs0Ppbw83oc="
puts Base64.decode64(s).bytes.map{|e| '%02x' % e}.join

Output: b48347d09c66af2bc1ea94641228b588160fec545e743a8812cd0fa5bc3cde87

like image 31
Yu Hao Avatar answered Oct 05 '22 09:10

Yu Hao