Monday, April 11, 2011

Storing SHA1 hash values in MySQL

Hi. I have a simple question which occured when I wanted to store the result of a SHA1 hash in a MySQL database:

How long should the VARCHAR field be in which I store the hash's result?

From stackoverflow
  • A SHA1 hash is 40 chars long!

    Douglas Leeder : In hex encoding...
  • I wouldn’t use VARCHAR with a variable length but a type with a fixed length. Because a SHA-1 value is always 160 bit long. The VARCHAR would just waste an additional byte for the length of the field that would always be the same.

    And I also wouldn’t store the value the SHA1 is returning. Because it uses just 4 bit per character and thus would need 160/4 = 40 characters. But if you use 8 bit per character, you would only need a 160/8 = 20 character long field.

    So I recommend you to use BINARY(20) and the UNHEX function to convert the SHA1 value to binary.

  • Output size of sha1 is 160 bits. Which is 160/8 == 20 chars (if you use 8-bit chars) or 160/16 = 10 (if you use 16-bit chars).

  • So the length is between 10 16-bit chars, and 40 hex digits.

    In any case decide the format you are going to store, and make the field a fixed size based on that format. That way you won't have any wasted space.

0 comments:

Post a Comment