我遇到了我试图在我的 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
更多人似乎遇到的这个问题。
任何帮助将非常感激!