require 'bcrypt'

module Security
    mattr_reader :cipher_iv, :cipher_key

    def self.encrypt(unencrypted_message, password = nil, iv = nil)
        cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
        cipher.encrypt()

        pass = password ? password : generate_token()
        cipher.key = @@cipher_key = create_key_from_pass(pass)
        cipher.iv  = @@cipher_iv  = iv || cipher.random_iv

        encrypted = cipher.update(unencrypted_message)
        encrypted << cipher.final

        Base64.encode64(encrypted).encode('utf-8')
    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

        begin
            decrypted = cipher.update(Base64.decode64(encrypted_message.encode('ascii-8bit')))
            decrypted << cipher.final
        rescue
            decrypted = ''
        end

        decrypted
    end

    def self.generate_token()
        BCrypt::Engine.generate_salt()
    end

    def self.save_cookies
        cookies[:key] = @@cipher_key
        cookies[:iv]  = @@cipher_iv
    end

    def self.create_key_from_pass(pass)
        Digest::SHA1.hexdigest(pass)
    end
end