I have a Rails 7.2.1 app that encrypts a column:
class Project < ApplicationRecord
encrypts :token
end
How do I decrypt the encrypted attribute with Ruby’s openssl library?
I have a Rails 7.2.1 app that encrypts a column:
class Project < ApplicationRecord
encrypts :token
end
How do I decrypt the encrypted attribute with Ruby’s openssl library?
The database contains JSON
record.attributes
# => "token"=>"7fc35ec16d6adc18fd485a679f7006b4eec64048b95d845bd030d29484b455a8"
data = JSON.parse(record.token_before_type_cast)
# => {"p"=>"0000000=", "h"=>{"iv"=>"0000000000000000", "at"=>"0000000000000000000000=="}}
I tried decrypting the data using OpenSSL::Cipher
but an error is thrown
data = {"p"=>"0000000=", "h"=>{"iv"=>"0000000000000000", "at"=>"0000000000000000000000=="}}
p = data.fetch("p")
iv = data.fetch("h").fetch("iv")
at = data.fetch("h").fetch("at")
key = Rails.application.config.active_record.encryption.primary_key
cipher = OpenSSL::Cipher.new("aes-256-gcm")
cipher.decrypt
cipher.key = key
cipher.iv = Base64.decode64(iv)
cipher.auth_tag = Base64.decode64(at)
s = cipher.update(Base64.decode64(p))
s << cipher.final
puts s
(app):in `final': OpenSSL::Cipher::CipherError
from (app):in `<main>'
Rails 7 has a horrible bug where encrypted columns don’t actually get encrypted. After decoding the fields using the script in the Rails issue tracker we implemented PostgreSQL encryption since we need to comply with HIPAA.
Encrypted attributes can only be decrypted by Rails. You can copy the unencrypted value to a new column or encode it with ActiveSupport::MessageEncryptor A simple way to encrypt and decrypt in Rails 5 | by Daveyon Mayne | Medium
rails generation migration AddUnencryptedTokenToProjects unencrypted_token:text Project.all.each do |project| project.save!(unencrypted_token: project.token) end