3

I was taking a look at this question regarding the field length and type to use for bcrypt hashes. Several the answers mention using the BINARY MYSQL column type. However, when reading from this column with the mysql node.js module, it reads BINARY columns into a buffer type rather than a string. The bcrypt compare function bcrypt.compare(password, hash, callback) does not like the buffer type:

Error: data and hash must be strings
    at node_modules/bcrypt/bcrypt.js:150:16

This leads me to two questions:

First, I assume that what I want to do is hash_buffer.toString(), but I notice in the documentation that there are different character encodings that can be used. I'm not sure what the correct encoding to use is since the data doesn't really represent actual characters. Since I want the binary data to remain unchanged, I would guess ASCII. Can anyone confirm this?

Second, I don't understand why not to use the CHAR data type. The hash is specifically made to be a printable string. I understand that the MYSQL comparisons might not be made as expected, but there is no appropriate time to search for or sort by a password hash anyways.

Community
  • 1
  • 1
bytesized
  • 1,502
  • 13
  • 22

1 Answers1

2

Generally speaking, it makes sense to use BINARY columns to store bcrypt hashes if MySQL is the one doing the comparison. A binary collation will prevent unwanted comparison results, e.g. 'A' being equal to 'a'; this makes a big difference in Base64 encoding.

However, if the comparison is exclusively performed in the application, you can save yourself the trouble and use a regular CHAR column for storing the hash.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 1
    How could MYSQL possibly be doing the comparison? You have to read the hash to get the salt and cost values before hashing the candidate password. – bytesized Jul 15 '15 at 04:48
  • 2
    @bytesized Bcrypt can also use md5 to generate a hash; it's a generic algorithm, so it's entirely possible that hashes could be looked up with a simple query; of course, i don't suggest you should do this. – Ja͢ck Jul 15 '15 at 04:50