From db1c0897001b12e2f9e298fda826233af0e9daa9 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 18 Nov 2018 16:47:15 -0600 Subject: [PATCH] Add Using BCrypt To Create And Check Hashed Passwords as a ruby til --- README.md | 3 ++- ...pt-to-create-and-check-hashed-passwords.md | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 ruby/using-bcrypt-to-create-and-check-hashed-passwords.md diff --git a/README.md b/README.md index 41a7911..82bf6fd 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_721 TILs and counting..._ +_722 TILs and counting..._ --- @@ -602,6 +602,7 @@ _721 TILs and counting..._ - [Up And Down With Integers](ruby/up-and-down-with-integers.md) - [Use A Case Statement As A Cond Statement](ruby/use-a-case-statement-as-a-cond-statement.md) - [Use dotenv In A Non-Rails Project](ruby/use-dotenv-in-a-non-rails-project.md) +- [Using BCrypt To Create And Check Hashed Passwords](ruby/using-bcrypt-to-create-and-check-hashed-passwords.md) - [Who Are My Ancestors?](ruby/who-are-my-ancestors.md) - [Zero Padding](ruby/zero-padding.md) diff --git a/ruby/using-bcrypt-to-create-and-check-hashed-passwords.md b/ruby/using-bcrypt-to-create-and-check-hashed-passwords.md new file mode 100644 index 0000000..1c1a6ab --- /dev/null +++ b/ruby/using-bcrypt-to-create-and-check-hashed-passwords.md @@ -0,0 +1,26 @@ +# Using BCrypt To Create And Check Hashed Passwords + +The [BCrypt](https://github.com/codahale/bcrypt-ruby) library is used under +the hood by gems like Devise in order to work with passwords securely. You +can use it to salt and hash a plain text password. You can also use it to +check whether an encrypted password matches some input password. + +```ruby +> include BCrypt +=> Object + +> encrypted_pass = Password.create('password') +=> "$2a$10$te3Y8wdSXf8/gWDeSP5z9eut7alThnuTvq1SvgQyJ1C57F.qit1uq" + +> Password.new(encrypted_pass) == "not_my_pass" +=> false + +> Password.new(encrypted_pass) == "password" +=> true +``` + +The `Password.create` method will salt and hash the given password. The +resulting encrypted password, if it is an instance of `Password`, can be +directly compared to a string. For good measure, in case the encrypted +password is a string, you can wrap it in a call to `Password.new` to ensure +you are working with a `Password` instance.