Class: CryptKeeper::Provider::PostgresPgp

Inherits:
PostgresBase show all
Defined in:
lib/crypt_keeper/provider/postgres_pgp.rb

Constant Summary

Constants inherited from PostgresBase

CryptKeeper::Provider::PostgresBase::INVALID_DATA_ERROR

Constants included from LogSubscriber::PostgresPgp

LogSubscriber::PostgresPgp::FILTER

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from PostgresBase

#encrypted?

Methods included from LogSubscriber::PostgresPgp

#sql

Methods inherited from Base

#dump, #load

Constructor Details

#initialize(options = {}) ⇒ PostgresPgp

Public: Initializes the encryptor

options - A hash, :key is required

10
11
12
13
14
15
16
17
18
# File 'lib/crypt_keeper/provider/postgres_pgp.rb', line 10

def initialize(options = {})
  ::ActiveSupport.run_load_hooks(:crypt_keeper_postgres_pgp_log, self)

  @key = options.fetch(:key) do
    raise ArgumentError, "Missing :key"
  end

  @pgcrypto_options = options.fetch(:pgcrypto_options, '')
end

Instance Attribute Details

#keyObject

Returns the value of attribute key


4
5
6
# File 'lib/crypt_keeper/provider/postgres_pgp.rb', line 4

def key
  @key
end

#pgcrypto_optionsObject

Returns the value of attribute pgcrypto_options


5
6
7
# File 'lib/crypt_keeper/provider/postgres_pgp.rb', line 5

def pgcrypto_options
  @pgcrypto_options
end

Instance Method Details

#decrypt(value) ⇒ Object

Public: Decrypts a string

Returns a plaintext string


33
34
35
36
37
38
39
40
41
42
# File 'lib/crypt_keeper/provider/postgres_pgp.rb', line 33

def decrypt(value)
  rescue_invalid_statement do
    if encrypted?(value)
      escape_and_execute_sql(["SELECT pgp_sym_decrypt(?, ?)",
        value, key])['pgp_sym_decrypt']
    else
      value
    end
  end
end

#encrypt(value) ⇒ Object

Public: Encrypts a string

Returns an encrypted string


23
24
25
26
27
28
# File 'lib/crypt_keeper/provider/postgres_pgp.rb', line 23

def encrypt(value)
  rescue_invalid_statement do
    escape_and_execute_sql(["SELECT pgp_sym_encrypt(?, ?, ?)",
      value.to_s, key, pgcrypto_options])['pgp_sym_encrypt']
  end
end

#search(records, field, criteria) ⇒ Object


44
45
46
47
48
49
50
51
52
53
# File 'lib/crypt_keeper/provider/postgres_pgp.rb', line 44

def search(records, field, criteria)
  if criteria.present?
    records
      .where.not("TRIM(BOTH FROM #{field}) = ?", "")
      .where("(pgp_sym_decrypt(cast(\"#{field}\" AS bytea), ?) = ?)",
             key, criteria)
  else
    records.where(field => criteria)
  end
end