Skip to content

Instantly share code, notes, and snippets.

@kyledrake
Created March 13, 2013 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyledrake/5148433 to your computer and use it in GitHub Desktop.
Save kyledrake/5148433 to your computer and use it in GitHub Desktop.
Idea for storing an SSN (or CC#, or anything confidential) on a database, preventing an attacker from looking at it if they've compromised the database the encrypted text is in, by hiding the private key on an offline machine, and encrypting the text with the public key (which it theoretically cannot read itself without the private key)
require 'openssl'
public_key = OpenSSL::PKey::RSA.new(File.read('./public.pem'))
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.encrypt
cipher.key = random_key = cipher.random_key
cipher.iv = random_iv = cipher.random_iv
encrypted_data = cipher.update('SSN number')
encrypted_data << cipher.final
encrypted_key = public_key.public_encrypt(random_key)
encrypted_iv = public_key.public_encrypt(random_iv)
# ^^ plain SSN number is thrown away, attacker only sees encrypted with public key
# On a private machine somewhere:
private_key = OpenSSL::PKey::RSA.new(File.read('./private.pem'), 'thepassword')
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.decrypt
cipher.key = private_key.private_decrypt(encrypted_key)
cipher.iv = private_key.private_decrypt(encrypted_iv)
decrypted_data = cipher.update(encrypted_data)
puts decrypted_data << cipher.final
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment