How long is the SHA256 hash?

MysqlSha256

Mysql Problem Overview


I'm going to run SHA256 on a password + salt, but I don't know how long to make my VARCHAR when setting up the MySQL database. What is a good length?

Mysql Solutions


Solution 1 - Mysql

A sha256 is 256 bits long -- as its name indicates.

Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64), or even a char(64), as the length is always the same, not varying at all.

And the demo :

$hash = hash('sha256', 'hello, world!');
var_dump($hash);

Will give you :

$ php temp.php
string(64) "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"

i.e. a string with 64 characters.

Solution 2 - Mysql

Encoding options for SHA256's 256 bits:

  1. Base64: 6 bits per char = CHAR(44) including padding character
  2. Hex: 4 bits per char = CHAR(64)
  3. Binary: 8 bits per byte = BINARY(32)

Solution 3 - Mysql

I prefer to use BINARY(32) since it's the optimized way!

You can place in that 32 hex digits from (00 to FF).

Therefore BINARY(32)!

Solution 4 - Mysql

Why would you make it VARCHAR? It doesn't vary. It's always 64 characters, which can be determined by running anything into one of the online SHA-256 calculators.

Solution 5 - Mysql

It will be fixed 64 chars, so use char(64)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTony StarkView Question on Stackoverflow
Solution 1 - MysqlPascal MARTINView Answer on Stackoverflow
Solution 2 - MysqlRickNZView Answer on Stackoverflow
Solution 3 - MysqlmarctremView Answer on Stackoverflow
Solution 4 - MysqlceejayozView Answer on Stackoverflow
Solution 5 - MysqlNoushadView Answer on Stackoverflow