static bool readCertificateIntoContext()

in platform/posix/transport/src/mbedtls_pkcs11_posix.c [522:593]


static bool readCertificateIntoContext( MbedtlsPkcs11Context_t * pContext,
                                        char * pLabelName,
                                        mbedtls_x509_crt * pCertificateContext )
{
    CK_RV pkcs11Ret = CKR_OK;
    CK_ATTRIBUTE template = { 0 };
    CK_OBJECT_HANDLE certificateHandle = 0;
    int32_t mbedtlsRet = -1;

    assert( pContext != NULL );
    assert( pLabelName != NULL );
    assert( pCertificateContext != NULL );

    /* Get the handle of the certificate. */
    pkcs11Ret = xFindObjectWithLabelAndClass( pContext->p11Session,
                                              pLabelName,
                                              strlen( pLabelName ),
                                              CKO_CERTIFICATE,
                                              &certificateHandle );

    if( ( pkcs11Ret == CKR_OK ) && ( certificateHandle == CK_INVALID_HANDLE ) )
    {
        pkcs11Ret = CKR_OBJECT_HANDLE_INVALID;
    }

    /* Query the certificate size. */
    if( pkcs11Ret == CKR_OK )
    {
        template.type = CKA_VALUE;
        template.ulValueLen = 0;
        template.pValue = NULL;
        pkcs11Ret = pContext->pP11FunctionList->C_GetAttributeValue( pContext->p11Session,
                                                                     certificateHandle,
                                                                     &template,
                                                                     1 );
    }

    /* Create a buffer for the certificate. */
    if( pkcs11Ret == CKR_OK )
    {
        template.pValue = malloc( template.ulValueLen );

        if( NULL == template.pValue )
        {
            LogError( ( "Failed to allocate %lu bytes of memory for certificate buffer.",
                        template.ulValueLen ) );
            pkcs11Ret = CKR_HOST_MEMORY;
        }
    }

    /* Export the certificate. */
    if( pkcs11Ret == CKR_OK )
    {
        pkcs11Ret = pContext->pP11FunctionList->C_GetAttributeValue( pContext->p11Session,
                                                                     certificateHandle,
                                                                     &template,
                                                                     1 );
    }

    /* Decode the certificate. */
    if( pkcs11Ret == CKR_OK )
    {
        mbedtlsRet = mbedtls_x509_crt_parse( pCertificateContext,
                                             ( const unsigned char * ) template.pValue,
                                             template.ulValueLen );
    }

    /* Free memory. */
    free( template.pValue );

    return( mbedtlsRet == 0 );
}