Method: OpenSSL::Cipher#final

Defined in:
ext/openssl/ossl_cipher.c

#finalString

Returns the remaining data held in the cipher object. Further calls to Cipher#update or Cipher#final are invalid. This call should always be made as the last call of an encryption or decryption operation, after having fed the entire plaintext or ciphertext to the Cipher instance.

When encrypting using an AEAD cipher, the authentication tag can be retrieved by #auth_tag after #final has been called.

When decrypting using an AEAD cipher, this method will verify the integrity of the ciphertext and the associated data with the authentication tag, which must be set by #auth_tag= prior to calling this method. If the verification fails, CipherError will be raised.

Returns:



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# File 'ext/openssl/ossl_cipher.c', line 439

static VALUE
ossl_cipher_final(VALUE self)
{
    EVP_CIPHER_CTX *ctx;
    int out_len;
    VALUE str;

    GetCipher(self, ctx);
    str = rb_str_new(0, EVP_CIPHER_CTX_block_size(ctx));
    if (!EVP_CipherFinal_ex(ctx, (unsigned char *)RSTRING_PTR(str), &out_len)) {
        /* For AEAD ciphers, this is likely an authentication failure */
        if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
            /* For AEAD ciphers, EVP_CipherFinal_ex failures are authentication tag verification failures */
            ossl_raise(eAuthTagError, "AEAD authentication tag verification failed");
        }
        else {
            /* For non-AEAD ciphers */
            ossl_raise(eCipherError, "cipher final failed");
        }
    }
    rb_str_set_len(str, out_len);

    return str;
}