Note that there are some explanatory texts on larger screens.

plurals
  1. POUnable to decrypt stored encrypted data
    primarykey
    data
    text
    <p>I'm running into issues with data I'm trying to store encrypted in my Rails 4 app. I've been looking at lots of questions related to this and there are many hints, feels like I'm almost there, but somehow it just won't decrypt the data. These are the two methods involved:</p> <pre><code>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 &lt;&lt; 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 &lt;&lt; cipher.final return decrypted end </code></pre> <p>And the I modified the read/writes to for example this:</p> <pre><code>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 </code></pre> <p>But when I try to read from it, it throws this <code>OpenSSL::Cipher::CipherError: bad decrypt</code> that more people seem to run into.</p> <p>Any help would be much appreciated!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload