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?

Andrey Fedorov
  • 9,148
  • 20
  • 67
  • 99

1 Answers1

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.

voithos
  • 68,482
  • 12
  • 101
  • 116
  • @AndreyFedorov: I liked your previous comment better. :) – voithos Sep 27 '12 at 02:40
  • 3
    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 :) – Andrey Fedorov Sep 28 '12 at 03:13
  • how about Getting hex representation of sha512 hash?? – AminFarajzadeh May 06 '17 at 08:25
  • @AminFarajzadeh: It would just be twice that - so, 128 hex digits. – voithos May 06 '17 at 16:18