Sha256: bcfeea814c99adc202df56c7545692b5c1e5564f5523b0a9ec41089664ae7763

Contents?: true

Size: 871 Bytes

Versions: 1

Compression:

Stored size: 871 Bytes

Contents

# frozen_string_literal: true
require "openssl"
require "base64"

module Obfuscate
  class << self
    def cipher
      OpenSSL::Cipher::Cipher.new("aes-256-cbc")
    end

    def cipher_key
      if defined?(Rails)
        Rails.application.secrets.secret_key_base
      elsif ENV["SECRET_KEY_BASE"]
        ENV["SECRET_KEY_BASE"]
      else
        raise NoCipherKey, "you must have a an SECRET_KEY_BASE or be in a rails enviroment"
      end
    end

    def decrypt(value)
      c = cipher.decrypt
      c.key = Digest::SHA256.digest(cipher_key)
      c.update(Base64.urlsafe_decode64(value.to_s)) + c.final
    rescue OpenSSL::Cipher::CipherError && ArgumentError
      return nil
    end

    def encrypt(value)
      c = cipher.encrypt
      c.key = Digest::SHA256.digest(cipher_key)
      Base64.urlsafe_encode64(c.update(value.to_s) + c.final)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bp_obfuscate-0.1.0 lib/bp_obfuscate/obfuscate.rb