Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting hex representation of sha256 hash using SJCL

The SJCL docs provide the following code as an example for sha256:

var bitArray = sjcl.hash.sha256.hash("message");  
var digest_sha256 = sjcl.codec.hex.fromBits(bitArray);  

The digest in that example being equal to a 64-character hex string, when I was expecting a 16-character hex string (256 bits = 16 hex characters). What am I missing? How can I get a 16-character digest of the hash?

like image 840
Andrey Fedorov Avatar asked Sep 26 '12 18:09

Andrey Fedorov


1 Answers

You're misunderstanding something. 256 bits does not equal 16 hex digits.

Think of it this way: 256 bits is equal to 32 bytes (8 bits in a byte). A byte (8 bits) can encode 256 (2^8) different values. A single hexadecimal digit (base-16) can encode 16 different values. How many hex digits do you need if you want to encode the same number of values as a byte? Two; two hex digits can encode 256 different values (16^2). So, if we need two hex digits per byte, and 256 bits is equal to 32 bytes, then that means we need 64 hex digits to represent the information that can be stored in 256 bits.

The hex digest is fine. It's supposed to be 64 characters.

like image 194
voithos Avatar answered Oct 01 '22 12:10

voithos