Sha256: 680f0b9b1e7921209d01c6a739546c901eceee8a7699cc80924c9a5c656623ea

Contents?: true

Size: 830 Bytes

Versions: 4

Compression:

Stored size: 830 Bytes

Contents

require "reversible_cryptography"
require "securerandom"

module Rtprov
  class Encryption
    KEY_FILE = "encryption_key".freeze

    attr_reader :key

    def self.load_key
      ENV["ENCRYPTION_KEY"] || (File.exist?(KEY_FILE) && File.read(KEY_FILE).strip) || raise("ENCRYPTION_KEY env or encryption_key file not found")
    end

    def self.encrypt(plain, key = load_key)
      new(key).encrypt(plain)
    end

    def self.decrypt(encrypted, key = load_key)
      new(key).decrypt(encrypted)
    end

    def self.generate_key
      SecureRandom.base64(512)
    end

    def initialize(key)
      @key = key.dup.freeze
    end

    def encrypt(plain)
      ReversibleCryptography::Message.encrypt(plain, key)
    end

    def decrypt(encrypted)
      ReversibleCryptography::Message.decrypt(encrypted, key)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rtprov-0.1.3 lib/rtprov/encryption.rb
rtprov-0.1.2 lib/rtprov/encryption.rb
rtprov-0.1.1 lib/rtprov/encryption.rb
rtprov-0.1.0 lib/rtprov/encryption.rb