Sha256: 14b6c6f91a9f9b7220bbbd1d86a3107f2bd08b5611e4a2325a9ea2c5c6839413

Contents?: true

Size: 1.16 KB

Versions: 3

Compression:

Stored size: 1.16 KB

Contents

require "openssl"
require "base64"

class ComplexConfig::Encryption
  class EncryptionError < StandardError; end

  class DecryptionFailed < EncryptionError; end

  def initialize(secret)
    @secret = secret
    @cipher = OpenSSL::Cipher.new('aes-128-gcm')
  end

  def encrypt(text)

    @cipher.encrypt
    @cipher.key = @secret
    iv = @cipher.random_iv
    @cipher.auth_data = ""

    encrypted = @cipher.update(Marshal.dump(text))
    encrypted << @cipher.final

    [
      encrypted,
      iv,
      @cipher.auth_tag
    ].map { |v| base64_encode(v) }.join('--')
  end

  def decrypt(text)
    encrypted, iv, auth_tag = text.split('--').map { |v| base64_decode(v) }

    auth_tag.nil? || auth_tag.bytes.length != 16 and
      raise DecryptionFailed, "auth_tag #{auth_tag.inspect} invalid"

    @cipher.decrypt
    @cipher.key = @secret
    @cipher.iv  = iv
    @cipher.auth_tag = auth_tag
    @cipher.auth_data = ""

    decrypted_data = @cipher.update(encrypted)
    decrypted_data << @cipher.final

    Marshal.load(decrypted_data)
  end

  private

  def base64_encode(x)
    ::Base64.strict_encode64(x)
  end

  def base64_decode(x)
    ::Base64.strict_decode64(x)
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
complex_config-0.11.2 lib/complex_config/encryption.rb
complex_config-0.11.1 lib/complex_config/encryption.rb
complex_config-0.11.0 lib/complex_config/encryption.rb