Class: Chamber::EncryptionMethods::Ssl

Inherits:
Object
  • Object
show all
Defined in:
lib/chamber/encryption_methods/ssl.rb

Constant Summary collapse

LARGE_DATA_STRING_PATTERN =

rubocop:disable Metrics/LineLength

%r{\A([A-Za-z0-9\+\/#]*\={0,2})#([A-Za-z0-9\+\/#]*\={0,2})#([A-Za-z0-9\+\/#]*\={0,2})\z}

Class Method Summary collapse

Class Method Details

.decrypt(key, value, decryption_keys) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/chamber/encryption_methods/ssl.rb', line 29

def self.decrypt(key, value, decryption_keys)
  if decryption_keys.nil?
    value
  else
    key, iv, decoded_string = value.
                                match(LARGE_DATA_STRING_PATTERN).
                                captures.
                                map do |part|
      Base64.strict_decode64(part)
    end
    key = decryption_keys.private_decrypt(key)

    cipher_dec = OpenSSL::Cipher.new('AES-128-CBC')

    cipher_dec.decrypt

    cipher_dec.key = key
    cipher_dec.iv = iv

    begin
      unencrypted_value = cipher_dec.update(decoded_string) + cipher_dec.final
    rescue OpenSSL::Cipher::CipherError
      raise Chamber::Errors::DecryptionFailure,
            'A decryption error occurred. It was probably due to invalid key data.'
    end

    begin
      _unserialized_value = YAML.load(unencrypted_value)
    rescue TypeError
      unencrypted_value
    end
  end
end

.encrypt(_key, value, encryption_keys) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/chamber/encryption_methods/ssl.rb', line 10

def self.encrypt(_key, value, encryption_keys)
  value = YAML.dump(value)
  cipher = OpenSSL::Cipher.new('AES-128-CBC')
  cipher.encrypt
  symmetric_key = cipher.random_key
  iv = cipher.random_iv

  # encrypt all data with this key and iv
  encrypted_data = cipher.update(value) + cipher.final

  # encrypt the key with the public key
  encrypted_key = encryption_keys.public_encrypt(symmetric_key)

  # assemble the resulting Base64 encoded data, the key
  Base64.strict_encode64(encrypted_key) + '#' +
  Base64.strict_encode64(iv) + '#' +
  Base64.strict_encode64(encrypted_data)
end