Created
February 17, 2013 19:22
-
-
Save vosechu/4972953 to your computer and use it in GitHub Desktop.
Simple Crypto module for encrypting and decrypting strings using a secret token stored in application config. Useful for creating email tokens which contain some data about the user for retrieval.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Crypto | |
def encrypt(string) | |
Base64.encode64(aes(Application.config.secret_token, string)).gsub /\s/, '' | |
end | |
def decrypt(string) | |
aes_decrypt(Application.config.secret_token, Base64.decode64(string.gsub(" ","+"))) | |
end | |
def aes(key,string) | |
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") | |
cipher.encrypt | |
cipher.key = Digest::SHA256.digest(key) | |
cipher.iv = initialization_vector = cipher.random_iv | |
cipher_text = cipher.update(string) | |
cipher_text << cipher.final | |
return initialization_vector + cipher_text | |
end | |
def aes_decrypt(key, encrypted) | |
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") | |
cipher.decrypt | |
cipher.key = Digest::SHA256.digest(key) | |
cipher.iv = encrypted.slice!(0,16) | |
d = cipher.update(encrypted) | |
d << cipher.final | |
rescue | |
return false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment