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.17.0 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.16.1 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.16.0.239 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.16.0.238 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.16.0.235 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.16.0.234 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.16.0.233 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.16.0 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.16.0.211 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.15.0.198 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.14.0.192 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.14.0.189 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.14.0.188 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.14.0.187 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.14.0 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.13.0.185 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.13.0.172 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.13.0 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.12.0.169 lib/sequel/plugins/attr_encrypted/simple_crypt.rb
umbrellio-sequel-plugins-0.12.0 lib/sequel/plugins/attr_encrypted/simple_crypt.rb