Module: DataEncryptor

Defined in:
lib/data_encryptor.rb,
lib/data_encryptor/version.rb

Constant Summary collapse

VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.decrypt(encrypted_data) ⇒ Object

Raises:

  • (ArgumentError)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/data_encryptor.rb', line 25

def self.decrypt(encrypted_data)
  raise ArgumentError, 'must specify a key' if @options[:key].to_s.empty?

  encrypted_data, iv = encrypted_data.split('--').map { |v| ::Base64.strict_decode64(v) }

  raise ArgumentError, 'encrypted data has invalid format' unless encrypted_data && iv

  cipher = new_cipher(method: :decrypt)
  cipher.iv = iv

  decrypted_data = cipher.update(encrypted_data)
  decrypted_data << cipher.final

  JSON.parse(decrypted_data)
end

.encrypt(data) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
# File 'lib/data_encryptor.rb', line 14

def self.encrypt(data)
  raise ArgumentError, 'must specify a key' if @options[:key].to_s.empty?

  cipher = new_cipher
  iv = cipher.random_iv

  decrypted = cipher.update(JSON.dump(data))
  decrypted << cipher.final
  "#{::Base64.strict_encode64(decrypted)}--#{::Base64.strict_encode64(iv)}"
end

.setup!(key:, algorithm: 'AES-256-CBC') ⇒ Object



10
11
12
# File 'lib/data_encryptor.rb', line 10

def self.setup!(key:, algorithm: 'AES-256-CBC')
  @options = { key: key, algorithm: algorithm }
end