Why base64 a sha1/sha256 hash?

tuna picture tuna · Mar 12, 2012 · Viewed 19.2k times · Source

can anybody tell me why amazon want a base64 of the hmac-sha1/sha256 hash?

http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/HMACAuth.html

I know that base64 is to represent binary date in ascii but sha1/sha256 is already ascii – I mean its only hex.

Thanks

Timo

Answer

zneak picture zneak · Mar 12, 2012

Those hashes are not ASCII–the reason you see hex digits is because the software you use to generate them takes the binary output of the digest and turns it into an ASCII string of hex digits.

For instance, the MD5 digest will fill an array of 16 bytes. You can also represent it as a string of 32 characters, but the most basic form of the digest is still the array of bytes.

When you change an array of bytes into a hex string, you need 8 bits (one full character) to represent every 4 bits of data. Although it's not frequently called that way, you could say that this uses "base16" encoding, since you're grabbing 4 bits at a time and mapping them to a 16-character alphabet.

Base64, on the other hand, grabs 6 bits at a time and maps them to a 64-character alphabet. This means that you need 8 bits (again, one full character) to represent every 6 bits of data, which has half the wasted bits of base16. A base16-encoded string will always be twice as big as the original; a base64-encoded string will only be four thirds as big. For a SHA256 hash, base16 does 64 bytes, but base64 does approximately 43.