Class: Keys::OpenSSL::Cipher

Inherits:
Object
  • Object
show all
Defined in:
lib/core/utils/openssl/cipher.rb

Instance Method Summary collapse

Constructor Details

#initialize(bytes: 32) ⇒ Cipher

Initialize the cipher with a random generated key and the aes-256-gcm algorithm

Parameters:

  • bytes (Integer) (defaults to: 32)

    the number of bytes to generate the key



19
20
21
22
23
24
25
# File 'lib/core/utils/openssl/cipher.rb', line 19

def initialize(bytes: 32)
  self.secure_key = SecureRandom.random_bytes(bytes)
  self.cipher = ::OpenSSL::Cipher.new('aes-256-gcm').encrypt

  # Configure the cipher key using the random generated key
  cipher.key = secure_key
end

Instance Method Details

#encrypt(value:) ⇒ Hash

Encrypt a value using the cipher

Parameters:

  • value (String)

    the value to encrypt

Returns:

  • (Hash)

    the encrypted value, the iv and the tag



30
31
32
33
34
35
36
# File 'lib/core/utils/openssl/cipher.rb', line 30

def encrypt(value:)
  iv = cipher.random_iv
  encrypted_value = cipher.update(value) + cipher.final
  tag = cipher.auth_tag

  { iv: iv.bytes, value: encrypted_value.bytes, tag: tag.bytes }
end

#secure_key_bytesArray

Fetch the bytes of the secure key

Returns:

  • (Array)

    the bytes of the secure key



40
41
42
# File 'lib/core/utils/openssl/cipher.rb', line 40

def secure_key_bytes
  secure_key.bytes
end