views:

4329

answers:

4

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?

+2  A: 

A SHA1 hash is 40 chars long!

schmilblick
In hex encoding...
Douglas Leeder
+38  A: 

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.

Gumbo
+2  A: 

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).

inazaruk
+1  A: 

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.

Douglas Leeder