int aws_cms_cipher_decrypt()

in source/cms.c [272:316]


int aws_cms_cipher_decrypt(
    struct aws_byte_buf *ciphertext,
    struct aws_byte_buf *key,
    struct aws_byte_buf *iv,
    struct aws_byte_buf *plaintext) {

    AWS_PRECONDITION(aws_byte_buf_is_valid(ciphertext));
    AWS_PRECONDITION(aws_byte_buf_is_valid(key));
    AWS_PRECONDITION(aws_byte_buf_is_valid(iv));

    if (key->len != EVP_CIPHER_key_length(EVP_aes_256_cbc())) {
        return AWS_OP_ERR;
    }

    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    if (ctx == NULL) {
        return AWS_OP_ERR;
    }

    /* Setup the decryption context */
    if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key->buffer, iv->buffer)) {
        EVP_CIPHER_CTX_free(ctx);
        return AWS_OP_ERR;
    }

    /* Output: ciphertext_len + the block length minus one */
    int ulen, flen;
    uint8_t out_text[ciphertext->len + EVP_CIPHER_CTX_block_size(ctx)];
    if (!EVP_DecryptUpdate(ctx, out_text, &ulen, ciphertext->buffer, ciphertext->len) ||
        !EVP_DecryptFinal_ex(ctx, &out_text[ulen], &flen)) {
        EVP_CIPHER_CTX_free(ctx);
        return AWS_OP_ERR;
    }

    /* Construct the plaintext output buffer. */
    struct aws_byte_cursor cursor = aws_byte_cursor_from_array(out_text, ulen + flen);
    if (AWS_OP_SUCCESS != aws_byte_buf_init_copy_from_cursor(plaintext, aws_nitro_enclaves_get_allocator(), cursor)) {
        EVP_CIPHER_CTX_free(ctx);
        return AWS_OP_ERR;
    }

    EVP_CIPHER_CTX_free(ctx);

    return AWS_OP_SUCCESS;
}