[英]Update database field in ruby on rails
我正在更新數據庫哈希算法。
我當前的系統在md5上運行,我想將其更改為BCrypt + salt 。
我的問題是,當一個舊用戶(其密碼在md5中散列的用戶)使用他的舊密碼登錄時,我想自動將密碼更改為數據庫中的BCrypt + salt。
if // check if the password stored in bcrypt
salt = IDA::Config.get_configuration('salt')
hash_password = BCrypt::Password.new(hash)
return (BCrypt::Password.create(salt['salt_value']+password) == (salt['salt_value']+password)) ? true : false
else // for users who's password encrypted in md5.
salt = IDA::Config.get_configuration('salt') // i"m getting a salt here
BCrypt::Password.create(salt['salt_value']+password) // Im getting a salted bcryptted password and I tried to put this into db manually and try to login it works perfectly
// I want to write this new salted password into db once the user is authenticated with his old password
return (Digest::MD5.hexdigest(password) == hash) ? true : false
我想在模型中寫這個。任何幫助將不勝感激。 謝謝
首先,BCrypt(庫和寶石庫)都處理鹽,因此您可以取消所有鹽業務。
其次,您真正想要的是一種重新散列所有記錄敏感數據(我假設的密碼)的方法。 因此,這是您的工作:
# First we need to make sure the bcrypt library is there
require 'bcrypt'
# Gather all of the records
records = YourModel.all
# Go over each of the records
records.each do |record|
# Check to see if the record has a bcrypt'ed password
unless record.is_bcrypt?
# If it doesn't take the value of password, unhash it, rehash it
record.password = BCrypt::Password.create Digest::MD5.hexdigest password
# If it saves correctly, mark the thing as being rehashed
record.is_bcrypt = true if record.save
end
end
有關詳細信息,請參見評論。 新字段is_bcrypt
只是這樣,您可以知道哪些記錄已被哈希處理,哪些尚未被哈希處理。 僅當他們也確實保存時才會發生。
完成此操作后,您確定所有與密碼有關的代碼都已重構,您可以刪除該字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.