From b26e4e3721302fe08085164d234159d33aa3c2af Mon Sep 17 00:00:00 2001 From: Tyler Hunt Date: Wed, 18 Jul 2012 11:47:01 -0700 Subject: [PATCH] Use constant-time string comparison algorithm. This borrows the string comparison code from Devise to prevent timing attacks (http://codahale.com/a-lesson-in-timing-attacks/). --- lib/bcrypt.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/bcrypt.rb b/lib/bcrypt.rb index b07678c..332cae0 100644 --- a/lib/bcrypt.rb +++ b/lib/bcrypt.rb @@ -170,7 +170,13 @@ def initialize(raw_hash) # Compares a potential secret against the hash. Returns true if the secret is the original secret, false otherwise. def ==(secret) - super(BCrypt::Engine.hash_secret(secret, @salt)) + hash = BCrypt::Engine.hash_secret(secret, @salt) + return false if self.empty? || hash.empty? || self.bytesize != hash.bytesize + l = self.unpack "C#{self.bytesize}" + + res = 0 + hash.each_byte { |byte| res |= byte ^ l.shift } + res == 0 end alias_method :is_password?, :==