1

我遇到了我试图在我的 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更多人似乎遇到的这个问题。

任何帮助将非常感激!

4

1 回答 1

3

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

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

于 2013-09-02T09:40:23.817 回答