According to the PKCS#11, X509 certificates are some kind of stored objects that their data class (CKA_CLASS
attribute) equals to CKO_CERTIFICATE
.
If you want to retrieve a certificate object from your token, all you need is to use C_GetAttributeValue
function.
Before doing this you may want find all x.509 certificates stored on your token:
CK_BBOOL _true = CK_TRUE;
CK_OBJECT_CLASS certClass = CKO_CERTIFICATE;
CK_CERTIFICATE_TYPE certType = CKC_X_509_ATTR_CERT;
CK_ATTRIBUTE certificateSearchTemplate[] = {
{CKA_CLASS, &certClass, sizeof(dataClass)},
{CKA_CERTIFICATE_TYPE, &certType, sizeof(certType)},
{CKA_TOKEN, &_true, sizeof(_true)}
};
CK_OBJECT_HANDLE hObject;
CK_ULONG ulObjectCount;
CK_RV rv = C_FindObjectsInit(hSession, certificateSearchTemplate, 3);
assert(rv == CKR_OK);
while (1) {
rv = C_FindObjects(hSession, &hObject, 1, &ulObjectCount);
if (rv != CKR_OK || ulObjectCount == 0)
break;
//hObject is handle of a x.509 certificate, so you can fetch your desired attributes from it using C_GetAttributeValue
getCertificateAttributes(hObject);
}
rv = C_FindObjectsFinal(hSession);
assert(rv == CKR_OK);
and in getCertificateAttributes
function you can get desired certificate attributes:
void getCertificateAttributes(CK_OBJECT_HANDLE hCert)
{
CK_ATTRIBUTE pTemplate[] = {
//List your desired attributes here
};
...
CK_RV rv = C_GetAttributeValue(hSession, hCert, &pTemplate, pTemplateLen);
if (rv == CKR_OK) {
//here you have your desired certificate attributes
}
}