int aws_attestation_rsa_decrypt()

in source/attestation.c [152:199]


int aws_attestation_rsa_decrypt(
    struct aws_allocator *allocator,
    struct aws_rsa_keypair *keypair,
    struct aws_byte_buf *ciphertext,
    struct aws_byte_buf *plaintext) {
    AWS_PRECONDITION(keypair != NULL && keypair->key_impl != NULL);
    AWS_PRECONDITION(aws_byte_buf_is_valid(ciphertext));

    if (allocator == NULL) {
        allocator = aws_nitro_enclaves_get_allocator();
    }

    EVP_PKEY *pkey = keypair->key_impl;

    /* Create the decryption context */
    EVP_PKEY_CTX *pkey_ctx = EVP_PKEY_CTX_new(pkey, NULL);
    if (pkey_ctx == NULL) {
        return AWS_OP_ERR;
    }

    /* Initialize the decryption context. */
    if (EVP_PKEY_decrypt_init(pkey_ctx) != 1 || EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_OAEP_PADDING) != 1 ||
        EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, EVP_sha256()) != 1 ||
        EVP_PKEY_CTX_set_rsa_oaep_md(pkey_ctx, EVP_sha256()) != 1) {

        EVP_PKEY_CTX_free(pkey_ctx);
        return AWS_OP_ERR;
    }

    /* Decrypt. RSA maximum encrypted data size is key modulus in bytes */
    size_t plain_data_len = EVP_PKEY_size(pkey);
    uint8_t plain_data[plain_data_len];

    if (EVP_PKEY_decrypt(pkey_ctx, plain_data, &plain_data_len, ciphertext->buffer, ciphertext->len) != 1) {
        EVP_PKEY_CTX_free(pkey_ctx);
        return AWS_OP_ERR;
    }

    EVP_PKEY_CTX_free(pkey_ctx);

    /* Construct the plain data byte buf */
    struct aws_byte_cursor cursor = aws_byte_cursor_from_array(plain_data, plain_data_len);
    if (AWS_OP_SUCCESS != aws_byte_buf_init_copy_from_cursor(plaintext, allocator, cursor)) {
        return AWS_OP_ERR;
    }

    return AWS_OP_SUCCESS;
}