Method: Lockbox::AES_GCM#decrypt

Defined in:
lib/lockbox/aes_gcm.rb

#decrypt(nonce, ciphertext, associated_data) ⇒ Object



28
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
# File 'lib/lockbox/aes_gcm.rb', line 28

def decrypt(nonce, ciphertext, associated_data)
  auth_tag, ciphertext = extract_auth_tag(ciphertext.to_s)

  fail_decryption if nonce.to_s.bytesize != nonce_bytes
  fail_decryption if auth_tag.to_s.bytesize != auth_tag_bytes

  cipher = OpenSSL::Cipher.new("aes-256-gcm")
  # do not change order of operations
  cipher.decrypt
  cipher.key = @key
  cipher.iv = nonce
  cipher.auth_tag = auth_tag
  # 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 ""
  # When decrypting, set it only after calling #decrypt, #key=, #iv= and #auth_tag= first.
  cipher.auth_data = associated_data || ""

  begin
    message = String.new
    message << cipher.update(ciphertext) unless ciphertext.to_s.empty?
    message << cipher.final
    message
  rescue OpenSSL::Cipher::CipherError
    fail_decryption
  end
end