Skip to content

Instantly share code, notes, and snippets.

@pahagon
Forked from colindean/cryptor.rb
Last active August 29, 2015 14:06
Show Gist options
  • Save pahagon/daddd347ad4e31042511 to your computer and use it in GitHub Desktop.
Save pahagon/daddd347ad4e31042511 to your computer and use it in GitHub Desktop.
#just make sure that you have the appropriate openssl gem required.
#inspiration: http://blog.agoragames.com/blog/2010/05/13/rubyreversibleencryption/
class Cryptor
self.encryption_type = "aes-256-cbc"
def self.encrypt(plaintext, key)
cipher = OpenSSL::Cipher::Cipher.new(self.encryption_type)
cipher.encrypt
cipher.key = key
cipher.iv = iv = cipher.random_iv
encrypted = cipher.update(plaintext) + cipher.final
encrypted = iv + encrypted
encrypted = Base64.encode64(encrypted)
encrypted
end
def self.decrypt(encrypted, key)
cipher = OpenSSL::Cipher::Cipher.new(self.encryption_type)
cipher.decrypt
cipher.key = key
encrypted = Base64.decode64(encrypted)
cipher.iv = encrypted.slice!(0,cipher.iv_len)
decrypted = cipher.update(encrypted) + cipher.final
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment