882090fc |
require 'bcrypt'
module Security
mattr_reader :cipher_iv, :cipher_key
|
16165255 |
def self.encrypt(unencrypted_message, password = nil, iv = nil) |
882090fc |
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.encrypt()
pass = password ? password : generate_token() |
16165255 |
cipher.key = @@cipher_key = create_key_from_pass(pass)
cipher.iv = @@cipher_iv = iv || cipher.random_iv |
882090fc |
encrypted = cipher.update(unencrypted_message)
encrypted << cipher.final |
0c651ead |
Base64.encode64(encrypted).encode('utf-8') |
882090fc |
end
def self.decrypt(encrypted_message, key, iv)
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.decrypt()
cipher.key = @@cipher_key = key
cipher.iv = @@cipher_iv = iv
|
83b96cf7 |
begin |
0c651ead |
decrypted = cipher.update(Base64.decode64(encrypted_message.encode('ascii-8bit'))) |
83b96cf7 |
decrypted << cipher.final
rescue
decrypted = ''
end
decrypted |
882090fc |
end
def self.generate_token()
BCrypt::Engine.generate_salt()
end
def self.save_cookies
cookies[:key] = @@cipher_key
cookies[:iv] = @@cipher_iv
end |
16165255 |
def self.create_key_from_pass(pass)
Digest::SHA1.hexdigest(pass)
end |
882090fc |
end |