gpt4 book ai didi

ruby-on-rails - 无法解密存储的加密数据

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:53 25 4
gpt4 key购买 nike

我在尝试以加密方式存储在我的 Rails 4 应用程序中时遇到了数据问题。我一直在看很多与此相关的问题并且有很多提示,感觉就像我快到了,但不知何故它不会解密数据。这是涉及的两种方法:

def encrypt( val, pwd_name )
cipher = OpenSSL::Cipher.new 'AES-128-CBC'
cipher.encrypt
iv = cipher.random_iv

pwd = encryptor_pwds[ pwd_name ]
salt = OpenSSL::Random.random_bytes 16
iter = 20000
key_len = cipher.key_len
digest = OpenSSL::Digest::SHA256.new

key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
cipher.key = key

encrypted = cipher.update val
encrypted << cipher.final

encrypted = Base64.encode64( encrypted ).encode('utf-8')
iv = Base64.encode64( iv ).encode('utf-8')
salt = Base64.encode64( salt ).encode('utf-8')

return { str: encrypted, iv: iv, salt: salt }
end



def decrypt( str, iv, salt, pwd_name )
cipher = OpenSSL::Cipher.new 'AES-128-CBC'
cipher.decrypt

str = Base64.decode64( str )
iv = Base64.decode64( iv )
salt = Base64.decode64( salt )

cipher.iv = iv

pwd = encryptor_pwds[ pwd_name ]
salt = salt
iter = 20000
key_len = cipher.key_len
digest = OpenSSL::Digest::SHA256.new

key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
cipher.key = key

decrypted = cipher.update str
decrypted << cipher.final
return decrypted
end

然后我将读/写修改为例如:

def email=(email)
unless email.nil?
set = encrypt(email, :email)
write_attribute( :email, set[:str] )
write_attribute( :email_iv, set[:iv] )
write_attribute( :email_salt, set[:salt] )
else
write_attribute( :email, nil )
end
end

def email
if read_attribute( :email ).nil? then read_attribute( :email ) else decrypt( read_attribute( :email ), read_attribute( :email_iv ), read_attribute( :email_salt ), :email ) end
end

但是当我尝试读取它时,它会抛出这个 OpenSSL::Cipher::CipherError: bad decrypt 似乎更多人会遇到这种情况。

如有任何帮助,我们将不胜感激!

最佳答案

这有点棘手,但问题不在于我的加密逻辑,而在于 Devise gem 中的过滤器。默认情况下在保存之前设计小写电子邮件地址,但因为我正在对它们进行加密和编码,所以我将区分大小写的 UTF8 字符串保存到数据库中。小写,将字符串解码回 ASCII 会导致与保存前不同的结果,这使得解密变得不可能。

现在,如果有人遇到这个问题,请在 config/initializers/devise.rb 中查找 case_insensitive_keys 设置,并确保它不包含您要的 key 保存加密。请记住,如果您这样做,最好要么自己将电子邮件小写,要么验证并禁止电子邮件中的大写字符,诸如此类。

关于ruby-on-rails - 无法解密存储的加密数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18535759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com