Class: EncryptedJsonb::JsonbEncryptor
- Inherits:
-
Object
- Object
- EncryptedJsonb::JsonbEncryptor
show all
- Defined in:
- lib/encrypted_jsonb/jsonb_encryptor.rb
Defined Under Namespace
Classes: Error, InvalidSignatureError
Instance Method Summary
collapse
Constructor Details
#initialize(primary_key:, deterministic_key:) ⇒ JsonbEncryptor
Returns a new instance of JsonbEncryptor.
13
14
15
16
17
18
19
20
21
|
# File 'lib/encrypted_jsonb/jsonb_encryptor.rb', line 13
def initialize(primary_key:, deterministic_key:)
ActiveRecord::Encryption.configure(
primary_key: primary_key,
deterministic_key: deterministic_key,
key_derivation_salt: SecureRandom.hex(32),
compressor: Zlib,
)
@encryptor = ActiveRecord::Encryption.encryptor
end
|
Instance Method Details
#decrypt(value) ⇒ Object
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# File 'lib/encrypted_jsonb/jsonb_encryptor.rb', line 38
def decrypt(value)
return if value.nil?
data = JSON.parse(value) if value.is_a?(String)
data ||= value
verify_signature!(data)
deep_transform(data["message"]) do |val|
next val unless val.is_a?(String)
deserialize_from_encryption(@encryptor.decrypt(val))
end
end
|
#encrypt(value) ⇒ Object
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
# File 'lib/encrypted_jsonb/jsonb_encryptor.rb', line 23
def encrypt(value)
return if value.nil?
encrypted_data = deep_transform(value) do |val|
next val unless val.is_a?(String) || val.is_a?(Numeric) || val.is_a?(TrueClass) || val.is_a?(FalseClass)
@encryptor.encrypt(serialize_for_encryption(val), cipher_options: { deterministic: true })
end
{
"message" => encrypted_data,
"signature" => @encryptor.encrypt(encrypted_data.to_json, cipher_options: { deterministic: true }),
}
end
|
#encrypt_for_query(value) ⇒ Object
52
53
54
55
56
|
# File 'lib/encrypted_jsonb/jsonb_encryptor.rb', line 52
def encrypt_for_query(value)
return if value.nil?
@encryptor.encrypt(serialize_for_encryption(value), cipher_options: { deterministic: true })
end
|