module Sequel::Plugins::AttrEncrypted::SimpleCrypt

Constants

SEPARATOR

Public Instance Methods

decrypt(string, key) click to toggle source
# File lib/sequel/plugins/attr_encrypted/simple_crypt.rb, line 19
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
encrypt(string, key) click to toggle source
# File lib/sequel/plugins/attr_encrypted/simple_crypt.rb, line 9
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

Private Instance Methods

dump(*values) click to toggle source
# File lib/sequel/plugins/attr_encrypted/simple_crypt.rb, line 43
def dump(*values)
  Array(values).map { |x| Base64.strict_encode64(x) }.join(SEPARATOR)
end
new_cipher(key) { |result| ... } click to toggle source
# File lib/sequel/plugins/attr_encrypted/simple_crypt.rb, line 32
def new_cipher(key)
  result = OpenSSL::Cipher.new("aes-256-gcm")
  yield(result)
  result.key = key
  result
end
parse(string) click to toggle source
# File lib/sequel/plugins/attr_encrypted/simple_crypt.rb, line 39
def parse(string)
  string.split(SEPARATOR).map { |x| Base64.strict_decode64(x) }
end