Question

I'm using MySql 5.5.32 and trying to reproduce some code in a stored procedure that we have in the business layer so I can set passwords for people using sql. It appears that there is something wrong with the SHA2 function though, but maybe I'm missing something:

SELECT length(SHA2("bob", 512))

Returns 128. Shouldn't it be 64?

SELECT length(SHA2("bob", 256))

Which returns 64, so it appears that either I missing something, or there is a bug in SHA2. Any ideas?

Was it helpful?

Solution 2

Comment was correct, even though the docs say that it returns binary string, it returns hex encoded string. To get the correct length use:

SELECT length(unhex(SHA2("bob", 512)));

OTHER TIPS

I coded the patch for the SHA2() function in 2005 and contributed it to MySQL (the developers then edited my code a bit to match their coding standards).

The function always returned a string of hex digits, just like all the other hash functions in MySQL.

You are probably reading this statement in the documentation:

As of MySQL 5.5.6, the return value is a nonbinary string in the connection character set. Before 5.5.6, the return value is a binary string.

I can see how a reader would think this means it returns binary bytes, but that's a misinterpretation.

What is actually meant by that is that the string had a binary character set. It's still a plaintext string of hex digits. In fact, none of the hash functions in MySQL return a string of bytes as if you ran UNHEX() on it, they all return strings of hex digits. The length of a string of hex digits is twice the length of the equivalent binary bytes.

If you don't know I mean by a binary character set, see What is binary character set?

SHA2() was changed to use the connection character set in 5.5.6, whereas other hash functions were changed in the same way in 5.5.3.

The SHA2(str, hash_length) function returns back a nonbinary string. Previously the SHA2 function in MySQL returned back a value of a binary string.

From the docs in the link I provided:

As of MySQL 5.5.6, the return value is a nonbinary string in the connection character set.

We can dissect all of this via the following SELECT statement:

SELECT SHA2("bob", 256) AS 'Hashed String', 
    UNHEX(SHA2("bob", 256)) AS 'Binary String',
    LENGTH(UNHEX(SHA2("bob", 256))) AS 'Byte Count'

Which via MySQL Workbench the output will result in this:

enter image description here

UPDATE Per Comment:

The UNHEX(str) function states in the documentation that it interprets each pair of characters in the inputted string as hexadecimal numbers. As for whether the input string is binary or nonbinary, the documentation answers that question for us here:

A NULL result can occur if the argument to UNHEX() is a BINARY column, because values are padded with 0x00 bytes when stored but those bytes are not stripped on retrieval.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top