in lib/FreeRTOS/network_transport/freertos_plus_tcp/using_mbedtls_pkcs11/using_mbedtls_pkcs11.c [567:671]
static CK_RV initializeClientKeys( SSLContext_t * pxCtx )
{
CK_RV xResult = CKR_OK;
CK_SLOT_ID * pxSlotIds = NULL;
CK_ULONG xCount = 0;
CK_ATTRIBUTE xTemplate[ 2 ];
mbedtls_pk_type_t xKeyAlgo = ( mbedtls_pk_type_t ) ~0;
/* Get the PKCS #11 module/token slot count. */
if( CKR_OK == xResult )
{
xResult = ( BaseType_t ) pxCtx->pxP11FunctionList->C_GetSlotList( CK_TRUE,
NULL,
&xCount );
}
/* Allocate memory to store the token slots. */
if( CKR_OK == xResult )
{
pxSlotIds = ( CK_SLOT_ID * ) pvPortMalloc( sizeof( CK_SLOT_ID ) * xCount );
if( NULL == pxSlotIds )
{
xResult = CKR_HOST_MEMORY;
}
}
/* Get all of the available private key slot identities. */
if( CKR_OK == xResult )
{
xResult = ( BaseType_t ) pxCtx->pxP11FunctionList->C_GetSlotList( CK_TRUE,
pxSlotIds,
&xCount );
}
/* Put the module in authenticated mode. */
if( CKR_OK == xResult )
{
xResult = ( BaseType_t ) pxCtx->pxP11FunctionList->C_Login( pxCtx->xP11Session,
CKU_USER,
( CK_UTF8CHAR_PTR ) configPKCS11_DEFAULT_USER_PIN,
sizeof( configPKCS11_DEFAULT_USER_PIN ) - 1 );
}
if( CKR_OK == xResult )
{
/* Get the handle of the device private key. */
xResult = xFindObjectWithLabelAndClass( pxCtx->xP11Session,
pkcs11configLABEL_DEVICE_PRIVATE_KEY_FOR_TLS,
CKO_PRIVATE_KEY,
&pxCtx->xP11PrivateKey );
}
if( ( CKR_OK == xResult ) && ( pxCtx->xP11PrivateKey == CK_INVALID_HANDLE ) )
{
xResult = CK_INVALID_HANDLE;
LogError( ( "Could not find private key." ) );
}
/* Query the device private key type. */
if( xResult == CKR_OK )
{
xTemplate[ 0 ].type = CKA_KEY_TYPE;
xTemplate[ 0 ].pValue = &pxCtx->xKeyType;
xTemplate[ 0 ].ulValueLen = sizeof( CK_KEY_TYPE );
xResult = pxCtx->pxP11FunctionList->C_GetAttributeValue( pxCtx->xP11Session,
pxCtx->xP11PrivateKey,
xTemplate,
1 );
}
/* Map the PKCS #11 key type to an mbedTLS algorithm. */
if( xResult == CKR_OK )
{
switch( pxCtx->xKeyType )
{
case CKK_RSA:
xKeyAlgo = MBEDTLS_PK_RSA;
break;
case CKK_EC:
xKeyAlgo = MBEDTLS_PK_ECKEY;
break;
default:
xResult = CKR_ATTRIBUTE_VALUE_INVALID;
break;
}
}
/* Map the mbedTLS algorithm to its internal metadata. */
if( xResult == CKR_OK )
{
memcpy( &pxCtx->privKeyInfo, mbedtls_pk_info_from_type( xKeyAlgo ), sizeof( mbedtls_pk_info_t ) );
pxCtx->privKeyInfo.sign_func = privateKeySigningCallback;
pxCtx->privKey.pk_info = &pxCtx->privKeyInfo;
pxCtx->privKey.pk_ctx = pxCtx;
}
/* Free memory. */
vPortFree( pxSlotIds );
return xResult;
}