Sha256: f73d1c206755f32b0b105bd24d03636d5c09db7fecc49998696d98c0cc937c48

Contents?: true

Size: 1.46 KB

Versions: 3

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true

# This is a module for encryption and decryption of attributes
require 'openssl'
require 'base64'

module LoggableActivity
  class EncryptionError < StandardError
  end

  module Encryption
    def self.encrypt(data, encryption_key)
      return nil if data.nil?
      return nil if encryption_key.nil?
      raise EncryptionError, 'Encryption failed: Invalid encryption key length' unless encryption_key.bytesize == 32

      cipher = OpenSSL::Cipher.new('AES-128-CBC').encrypt
      cipher.key = Digest::SHA1.hexdigest(encryption_key)[0..15]
      encrypted = cipher.update(data.to_s) + cipher.final
      Base64.encode64(encrypted)
    rescue OpenSSL::Cipher::CipherError => e
      raise EncryptionError, "Encryption failed: #{e.message} ***"
    end

    def self.decrypt(data, encryption_key)
      return I18n.t('loggable.activity.deleted') if blank?(data) || blank?(encryption_key)

      cipher = OpenSSL::Cipher.new('AES-128-CBC').decrypt
      cipher.key = Digest::SHA1.hexdigest(encryption_key)[0..15]
      decrypted_data = Base64.decode64(data)
      decrypted_output = cipher.update(decrypted_data) + cipher.final
      raise 'Decryption failed: Invalid UTF-8 output' unless decrypted_output.valid_encoding?

      decrypted_output.force_encoding('UTF-8')
    rescue OpenSSL::Cipher::CipherError => e
      raise EncryptionError, e.message
    end

    def self.blank?(value)
      value.respond_to?(:empty?) ? value.empty? : !value
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
loggable_activity-0.1.39 lib/loggable_activity/encryption.rb
loggable_activity-0.1.38b lib/loggable_activity/encryption.rb
loggable_activity-0.1.36 lib/loggable_activity/encryption.rb