Johan Polson
Johan Polson

Reputation: 117

make an identical sha512 in C # and mysql

I want to make an identical sha512 in C# and mysql.

c#

System.Security.Cryptography.SHA512.Create().ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes("test"));

C# results Length 64

238 38 176 221 74 247 231 73 170 26 142 227 193 10 233 146 63 97 137 128 119 46 71 63 136 25 165 212 148 14 13 178 122 193 133 248 160 225 213 248 79 136 188 136 127 214 123 20 55 50 195 4 204 95 169 173 142 111 87 245 0 40 168 255 

mysql

INSERT INTO users_table (password) VALUES (  SHA2("test", 512));
// password is a BINARY(128)

mysql results Length 128

101 101 50 54 98 48 100 100 52 97 102 55 101 55 52 57 97 97 49 97 56 101 101 51 99 49 48 97 101 57 57 50 51 102 54 49 56 57 56 48 55 55 50 101 52 55 51 102 56 56 49 57 97 53 100 52 57 52 48 101 48 100 98 50 55 97 99 49 56 53 102 56 97 48 101 49 100 53 102 56 52 102 56 56 98 99 56 56 55 102 100 54 55 98 49 52 51 55 51 50 99 51 48 52 99 99 53 102 97 57 97 100 56 101 54 102 53 55 102 53 48 48 50 56 97 56 102 102 

I compare them in bytes from, but the results are different from each other : (

thankful for help!

best regards johan

Upvotes: 2

Views: 340

Answers (1)

Jon
Jon

Reputation: 437454

MySql is returning a hex-encoded string:

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; see the notes at the beginning of this section about using the value as a nonbinary string.

You can tell this is happening because C#'s first byte is 238, which is 0xee, and the ASCII code for e is 101 -- MySql's return begins with 101 101. So you just need to turn the hex-encoded string into a binary string again with UNHEX (but only on MySql > 5.5.6).

So to receive identical results in your case:

INSERT INTO users_table (password) VALUES (UNHEX(SHA2("test", 512))); 

And using MySql conditional comments (oh the ugliness!) to be portable across versions:

INSERT INTO users_table (password) VALUES (/*!50506 UNHEX(*/SHA2("test",512)/*!50506 )*/); 

Upvotes: 2

Related Questions