2019-07-30 21:29:24 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-06-12 20:03:43 +00:00
|
|
|
# License: AGPL-3.0-or-later WITH WTO-AP-3.0-or-later
|
|
|
|
# Full license explanation at https://github.com/houdiniproject/houdini/blob/master/LICENSE
|
2018-03-25 17:30:42 +00:00
|
|
|
require 'openssl'
|
|
|
|
|
|
|
|
# This module is useful for encrypting columns into the database
|
|
|
|
# For the encrypted column, store it as "text" types
|
|
|
|
|
|
|
|
# .key is stored in ENV['CYPHER_KEY']
|
|
|
|
# .iv, .auth_tag both are stored with the encrypted data
|
|
|
|
|
|
|
|
module Cypher
|
|
|
|
def self.encrypt(data)
|
|
|
|
cipher = create_cipher
|
|
|
|
cipher.encrypt
|
|
|
|
cipher.key = Base64.decode64(ENV['CYPHER_KEY'])
|
|
|
|
iv = cipher.random_iv
|
|
|
|
encrypted = cipher.update(data) + cipher.final
|
2019-07-30 21:29:24 +00:00
|
|
|
{ iv: Base64.encode64(iv), key: Base64.encode64(encrypted) }
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# hash must have properties for :iv and :key
|
|
|
|
def self.decrypt(hash)
|
2019-07-30 21:29:24 +00:00
|
|
|
iv = Base64.decode64(hash['iv'])
|
|
|
|
encrypted = Base64.decode64(hash['key'])
|
2018-03-25 17:30:42 +00:00
|
|
|
decipher = create_cipher
|
|
|
|
decipher.decrypt
|
|
|
|
decipher.key = Base64.decode64(ENV['CYPHER_KEY'])
|
|
|
|
decipher.iv = iv
|
|
|
|
|
2019-07-30 21:29:24 +00:00
|
|
|
decipher.update(encrypted) + decipher.final
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
|
|
|
|
2019-07-30 21:29:24 +00:00
|
|
|
private
|
2018-03-25 17:30:42 +00:00
|
|
|
|
|
|
|
def self.create_cipher
|
|
|
|
OpenSSL::Cipher::AES256.new(:CBC)
|
|
|
|
end
|
|
|
|
end
|