Method: Lockbox::AES_GCM#encrypt

Defined in:
lib/lockbox/aes_gcm.rb

#encrypt(nonce, message, associated_data) ⇒ Object



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

def encrypt(nonce, message, associated_data)
  cipher = OpenSSL::Cipher.new("aes-256-gcm")
  # do not change order of operations
  cipher.encrypt
  cipher.key = @key
  cipher.iv = nonce
  # From Ruby 2.5.3 OpenSSL::Cipher docs:
  # If no associated data shall be used, this method must still be called with a value of ""
  # In encryption mode, it must be set after calling #encrypt and setting #key= and #iv=
  cipher.auth_data = associated_data || ""

  ciphertext = String.new
  ciphertext << cipher.update(message) unless message.empty?
  ciphertext << cipher.final
  ciphertext << cipher.auth_tag
  ciphertext
end