Skip to content

Instantly share code, notes, and snippets.

@technicalpickles
Forked from trevmex/string.rb
Created September 10, 2010 14:33
Show Gist options
  • Save technicalpickles/573731 to your computer and use it in GitHub Desktop.
Save technicalpickles/573731 to your computer and use it in GitHub Desktop.
require 'openssl'
require 'base64'
# Extend sString to include encryption and decryption method
#
# For this to work, you must place this in the lib directory of your Rails project.
# You will also need three files in your config directory:
# * public.pem: Your public key file
# * private.pem: Your private key file
# * passphrase.txt: Your passphrase
String.class_eval do
def encrypt
public_key_file = File.join(File.dirname(__FILE__), '..', 'config', 'public.pem')
public_key = OpenSSL::PKey::RSA.new(File.read(public_key_file))
Base64.encode64(public_key.public_encrypt(self))
end
def decrypt
private_key_file = File.join(File.dirname(__FILE__), '..', 'config', 'private.pem')
passphrase_file = File.join(File.dirname(__FILE__), '..', 'config', 'passphrase.txt')
private_key = OpenSSL::PKey::RSA.new(File.read(private_key_file), File.read(passphrase_file).rstrip)
private_key.private_decrypt(Base64.decode64(self))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment