9

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?

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@AndreyFedorov: I liked your previous comment better. :)
Hah! I had this thought that if Google somehow placed this question high on the results page for my name, no one would ever hire me as a programmer again. For the record, my original comment was something along the lines of "Right. I confused 'a hex char has 16 possible values' with 'a hex char has 16 bits of information'". In my defense, I didn't sleep much the night before :)
how about Getting hex representation of sha512 hash??
@AminFarajzadeh: It would just be twice that - so, 128 hex digits.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.