Sha256: b467f9f6e95288daea89cd987ece73c7c7b3eef33ba72628216e54b1b00908db

Contents?: true

Size: 1.02 KB

Versions: 40

Compression:

Stored size: 1.02 KB

Contents

# frozen_string_literal: true

module Sequel::Plugins::AttrEncrypted::SimpleCrypt
  extend self
  require "base64"

  SEPARATOR = "$"

  def encrypt(string, key)
    return unless string.is_a?(String) && !string.empty?

    encryptor = new_cipher(key, &:encrypt)
    iv = encryptor.random_iv

    encrypted = encryptor.update(string) + encryptor.final
    dump(encrypted, iv, encryptor.auth_tag)
  end

  def decrypt(string, key)
    encrypted, iv, auth_tag = parse(string) if string.is_a?(String)
    return if [encrypted, iv, auth_tag].any?(&:nil?)

    decryptor = new_cipher(key, &:decrypt)
    decryptor.iv = iv
    decryptor.auth_tag = auth_tag

    decryptor.update(encrypted) + decryptor.final
  end

  private

  def new_cipher(key)
    result = OpenSSL::Cipher.new("aes-256-gcm")
    yield(result)
    result.key = key
    result
  end

  def parse(string)
    string.split(SEPARATOR).map { |x| Base64.strict_decode64(x) }
  end

  def dump(*values)
    Array(values).map { |x| Base64.strict_encode64(x) }.join(SEPARATOR)
  end
end

Version data entries

40 entries across 40 versions & 1 rubygems

Version Path
umbrellio-sequel-plugins-0.12.0.159 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.11.0.143 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.10.0.101 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.10.0.100 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.10.0.86 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.9.0.79 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.9.0.76 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.8.0.73 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.7.0.52 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.6.0.46 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.6.0 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.6.0.36 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.5.1.27 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.5.1.26 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.5.1.25 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.5.1.18 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.5.1.17 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.5.1 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.5.0 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.4.0.164 lib/sequel/plugins/attr_encrypted/simple_crypt.rb