Skip to content

Instantly share code, notes, and snippets.

@iamkevinlowe
Created February 16, 2017 23:53
Show Gist options
  • Save iamkevinlowe/ef1871d2e00e8db7572c7b0dc6fb6026 to your computer and use it in GitHub Desktop.
Save iamkevinlowe/ef1871d2e00e8db7572c7b0dc6fb6026 to your computer and use it in GitHub Desktop.
Crypto module to encrypt/decrypt with AES128 and AES256
module Crypto
module AES128
class << self
def encrypt(data)
aes = OpenSSL::Cipher.new('AES-128-CBC')
aes.encrypt
aes.key = Digest::MD5.digest(ENV['SECRET_KEY'])
crypt = aes.update(data) + aes.final
Base64.urlsafe_encode64(crypt)
end
def decrypt(data)
aes = OpenSSL::Cipher.new('AES-128-CBC')
aes.decrypt
aes.key = Digest::MD5.digest(ENV['SECRET_KEY'])
tempkey = Base64.urlsafe_decode64(data)
aes.update(tempkey) + aes.final
end
end
end
module AES256
class << self
def encrypt(data)
aes = OpenSSL::Cipher.new('AES-256-CBC')
aes.encrypt
aes.key = Digest::SHA256.digest(ENV['SECRET_KEY'])
crypt = aes.update(data) + aes.final
Base64.urlsafe_encode64(crypt)
end
def decrypt(data)
aes = OpenSSL::Cipher.new('AES-256-CBC')
aes.decrypt
aes.key = Digest::SHA256.digest(ENV['SECRET_KEY'])
tempkey = Base64.urlsafe_decode64(data)
aes.update(tempkey) + aes.final
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment