Skip to content

Instantly share code, notes, and snippets.

@DCarper
Created October 21, 2011 18:37
Show Gist options
  • Select an option

  • Save DCarper/1304596 to your computer and use it in GitHub Desktop.

Select an option

Save DCarper/1304596 to your computer and use it in GitHub Desktop.
class Sensitive < ActiveRecord::Base
attr_accessor :plain_data
attr_protected :encrypted_data, :encrypted_key, :encrypted_iv
before_save :encrypt_sensitive
def decrypt_sensitive(password)
if self.encrypted_data
private_key = OpenSSL::PKey::RSA.new(File.read(APP_CONFIG['private_key']),password)
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.decrypt
cipher.key = private_key.private_decrypt(self.encrypted_key)
cipher.iv = private_key.private_decrypt(self.encrypted_iv)
decrypted_data = cipher.update(self.encrypted_data)
decrypted_data << cipher.final
else
''
end
end
def clear_sensitive
self.encrypted_data = self.encrypted_key = self.encrypted_iv = nil
end
private
def encrypt_sensitive
if !self.plain_data.blank?
public_key = OpenSSL::PKey::RSA.new(File.read(APP_CONFIG['public_key']))
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.encrypt
cipher.key = random_key = cipher.random_key
cipher.iv = random_iv = cipher.random_iv
self.encrypted_data = cipher.update(self.plain_data)
self.encrypted_data << cipher.final
self.encrypted_key = public_key.public_encrypt(random_key)
self.encrypted_iv = public_key.public_encrypt(random_iv)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment