Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby-BCrypt: Specify salt

Is it possible to specify which salt is used when encrypting strings with ruby-bcrypt?

I know it's not very safe, but I only use it for not-high security data: I have a plattform, and when a user deletes his account, i still want to know if this user was registered with this email before (due to free credits on registration).

So I thought I will encrypt the email with Bcrypt (before deletion) and later I can query afterwards if this hash exists when the user wants to register again with this email address?

But now i realized that bcrypt always procudes a new salt... Can I specify the salt somehow?

Thanks,

DISCLAIMER/ATTENTION:

IN GENERAL YOU SHOULD NEVER SPECIFY SALTS DIRECTLY - ITS INSECURE!!!

like image 281
BvuRVKyUVlViVIc7 Avatar asked Dec 04 '22 08:12

BvuRVKyUVlViVIc7


1 Answers

Yes you can:

BCrypt::Engine.hash_secret( '[email protected]', "$2a$10$ThisIsTheSalt22CharsX." )

The first 7 chars are not technically the salt, they identify the bcrypt algorithm, and set the number of iterations to 2**10 == 1024. For simplicity though, Ruby's bcrypt module treats the first characters as part of the salt, so you need to as well. You should probably use

BCrypt::Engine.generate_salt

To create your shared salt, as that doesn't rely on you to come up with something "random".

To improve security a little, you could keep the salt separate from the searchable hashes, and treat it much like any other secret data within the app. For example, make it a config item, and only store the hash part of the bcrypt for searching (the first part is redundant data for you anyhow and will reduce performance of the search, although that effect is probably very small):

email = '[email protected]'
full_hash = BCrypt::Engine.hash_secret( email, settings.email_search_salt )
searchable_hash = full_hash[29,31]
# Either store or search . . .
like image 82
Neil Slater Avatar answered Dec 30 '22 11:12

Neil Slater