Class: ComplexConfig::Encryption

Inherits:
Object
  • Object
show all
Defined in:
lib/complex_config/encryption.rb

Overview

A class that provides encryption and decryption services using AES-128-GCM

This class handles the encryption and decryption of configuration data using OpenSSL’s AES-128-GCM cipher mode. It manages the encryption key validation, initialization vector generation, and authentication tag handling required for secure encrypted communication.

Instance Method Summary collapse

Constructor Details

#initialize(secret) ⇒ Encryption

Initializes a new encryption instance with the specified secret key

This method sets up the encryption object by validating the secret key length and preparing the OpenSSL cipher for AES-128-GCM encryption operations

Raises:



25
26
27
28
29
30
# File 'lib/complex_config/encryption.rb', line 25

def initialize(secret)
  @secret = secret
  @secret.size != 16 and raise ComplexConfig::EncryptionKeyInvalid,
    "encryption key #{@secret.inspect} must be 16 bytes"
  @cipher = OpenSSL::Cipher.new('aes-128-gcm')
end

Instance Method Details

#decrypt(text) ⇒ Object

The decrypt method decodes encrypted text using AES-128-GCM decryption

Raises:



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/complex_config/encryption.rb', line 70

def decrypt(text)
  encrypted, iv, auth_tag = text.split('--').map { |v| base64_decode(v) }

  auth_tag.nil? || auth_tag.bytes.length != 16 and
    raise ComplexConfig::DecryptionFailed, "auth_tag was invalid"

  @cipher.decrypt
  @cipher.key = @secret
  @cipher.iv  = iv
  @cipher.auth_tag = auth_tag
  @cipher.auth_data = ""

  decrypted_data = @cipher.update(encrypted)
  decrypted_data << @cipher.final

  Marshal.load(decrypted_data)
rescue OpenSSL::Cipher::CipherError
  raise ComplexConfig::DecryptionFailed, "decryption failed with this key"
end

#encrypt(text) ⇒ String

The encrypt method encodes text using AES-128-GCM encryption

This method takes a text input and encrypts it using the OpenSSL cipher configured with AES-128-GCM mode. It generates a random initialization vector and authentication tag, then combines the encrypted data, IV, and auth tag into a base64-encoded string separated by ‘–’

encryption



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/complex_config/encryption.rb', line 45

def encrypt(text)
  @cipher.encrypt
  @cipher.key = @secret
  iv = @cipher.random_iv
  @cipher.auth_data = ""

  encrypted = @cipher.update(Marshal.dump(text))
  encrypted << @cipher.final

  [
    encrypted,
    iv,
    @cipher.auth_tag
  ].map { |v| base64_encode(v) }.join('--')
end