⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cert-installer.c

📁 非常不错的CSP源码学习
💻 C
📖 第 1 页 / 共 3 页
字号:
        }        /**  - Iterator seeked by 64.*/    }    /** - Finish digest, get hashed data lenth.*/    rv = p11->C_DigestFinal(pCertInfo->hSession, NULL, &hashLen);    if(rv != CKR_OK)    {        return FALSE;    }    /** - Allocate space for hashed data.*/    result = (BYTE *) HeapAlloc(heapHandle, HEAP_ZERO_MEMORY,                                 hashLen);    if(result == NULL)    {        SetLastError(NTE_NO_MEMORY);        return FALSE;    }        /** - Fill hashed data with hash result.*/    rv = p11->C_DigestFinal(pCertInfo->hSession, result, &hashLen);    if(rv != CKR_OK)    {        return FALSE;    }    /** - Build the hash human readable 32 chars string.*/    strcpy(pCertInfo->keyHash,"");    for(i=0;i<20;i++)    {        byte = *(((unsigned char *)result)+i);        if(byte < 16)        {            sprintf(byteChar, "0%x", byte);        }        else        {            sprintf(byteChar, "%x", byte);        }        strcat(pCertInfo->keyHash, byteChar);    }    /** - Free hash.*/    HeapFree(heapHandle, 0, result);    /** - Free object modulus.*/    HeapFree(heapHandle, 0, forObjectModulus.pValue);    printf("%s contains SHA1(%x) = %s\n",pCertInfo->tokenLabel,                                         pCertInfo->keyId,                                         pCertInfo->keyHash);    return TRUE;}/** \brief Find certificates. * *  Scan the slot, find a card and find certificate on this card. *  Remember only certificate associated with existing key. * *  \param certificatesList Pointer to the adress where the pointer to the *                          certificates list will be stored. *  \return Number of founded certificates. */int findCertificates(){    CK_SLOT_ID slotId = NO_SLOT; /* The currently used slot. Default: no slot.*/    CK_SLOT_ID * slots=NULL; /* Available slots list.*/    CK_ULONG slotsNumber=0; /* Number of available slots.*/    CERTIFICATE_INFO certificateInfo; /* Info of the current certificate.*/    CK_SLOT_INFO slotInfo; /* Info of the current slot.*/    CK_TOKEN_INFO tokenInfo; /* Info of the current token.*/    CK_OBJECT_HANDLE hCerts[64]; /* Maximum 64 cert per token.*/    int certificatesNumber; /* Number of founded correct certificates.*/    int i;  /* Iterator.*/    CK_RV rv; /* PKCS #11 API return value. */    CK_ULONG slotIndex; /* Actual slot number.*/    CK_ATTRIBUTE template[1];   /* Research attributes template.*/    CK_ULONG objectsFoundNumber; /* Number of found objects.*/    CK_OBJECT_CLASS certClass = CKO_CERTIFICATE; /* Certificate object class.*/    CK_ATTRIBUTE forObjectLabel = {CKA_LABEL, NULL, 0}; /* Attribute for cert                                                            LABEL.*/    char tokenLabel[33]; /* Token Label.*/    CK_SESSION_HANDLE hSession; /* Handle to the session used to access the cert.*/        /** - RAZ of certificates number.*/    certificatesNumber = 0;    /** - Initialize the cryptoki library. */    if (!initializeP11())    {        return FALSE;    }    /* - Get the number of slots. */    rv = p11->C_GetSlotList(FALSE, NULL, &slotsNumber);    if (!(rv == CKR_OK || rv == CKR_BUFFER_TOO_SMALL))    {        SetLastError(ERROR_DEVICE_NOT_AVAILABLE);        return FALSE;    }        /* - Allocate memory for slots list. */    slots = (CK_SLOT_ID *) HeapAlloc(heapHandle, HEAP_ZERO_MEMORY, slotsNumber*sizeof(CK_SLOT_ID));    if (slots == NULL)    {        SetLastError(NTE_NO_MEMORY);        return FALSE;    }    /* - Fill the allocated memory with the slots list. */    rv = p11->C_GetSlotList(FALSE, slots, &slotsNumber);    if (rv != CKR_OK)    {        SetLastError(ERROR_DEVICE_NOT_AVAILABLE);        return FALSE;    }    slotIndex=0;    /* - Try each slot to find the correct one, with the correct card. */    while(slotIndex<slotsNumber)    {        slotId = slots[slotIndex];                /**  - Get the current slot info.*/        rv = p11->C_GetSlotInfo(slotId, &slotInfo);        if (rv == CKR_OK)   /* The slot is available.*/        {            /**   - Get the slot info.*/            if(slotInfo.flags & CKF_TOKEN_PRESENT) /* There is a token in it. */            {                 rv = p11->C_OpenSession(slotId, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL,                                        NULL, &hSession);                if (rv == CKR_OK)                {                    /** - Get token (card) information. */                    rv = p11->C_GetTokenInfo(slotId, &tokenInfo);                    if (rv == CKR_OK)                    {                        strncpy(tokenLabel, tokenInfo.label, 32);                        tokenLabel[32] = '\0';                        printf("Browsing %s...\n", tokenLabel);                        template[0].type = CKA_CLASS;                        template[0].pValue = &certClass;                        template[0].ulValueLen = sizeof(certClass);                                                /** - Initiate the certificate research.*/                        rv = p11->C_FindObjectsInit(hSession,                                                    template, 1);                         if (rv != CKR_OK)                        {                            return FALSE;                        }                        /** - Find the corresponding objects.*/                         rv = p11->C_FindObjects(hSession,                                                 hCerts, 64,                                                 &objectsFoundNumber);                        if (rv != CKR_OK)                        {                            return FALSE;                        }                        /** - Close the certificate research.*/                        rv = p11->C_FindObjectsFinal(hSession);                        if (rv != CKR_OK)                        {                            SetLastError(NTE_BAD_KEYSET);                            return 0;                        }                        /** - Browse founded objects. */                        for(i=0; i<objectsFoundNumber; i++)                        {                            certificateInfo.hSession = hSession;                            certificateInfo.hCert = hCerts[i];                            if(pubKeyPresent(tokenInfo,                                             &certificateInfo))                            {                                if(!loadDerCert(&certificateInfo))                                {                                    return 0;                                }                                /** - Get the first cert LABEL attribute size.*/                                rv = p11->C_GetAttributeValue(hSession,                                                               hCerts[i], &forObjectLabel,                                                              1);                                if(rv != CKR_OK)                                {                                    return FALSE;                                }                                /** - Allocate memory for the wanted attribute.*/                                forObjectLabel.pValue = HeapAlloc(heapHandle,                                                                  HEAP_ZERO_MEMORY,                                                            forObjectLabel.ulValueLen+1);                                /** - Get the first cert LABEL attribute.*/                                rv = p11->C_GetAttributeValue(hSession,                                                              hCerts[i], &forObjectLabel, 1);                                certificateInfo.label = forObjectLabel.pValue;                                forObjectLabel.pValue = NULL;                                certificateInfo.label[forObjectLabel.ulValueLen] = '\0';                                /** - One more certificate.*/                                certificatesList[certificatesNumber].hSession =                                                                 certificateInfo.hSession;                                certificatesList[certificatesNumber].hCert =                                                                certificateInfo.hCert;                                certificatesList[certificatesNumber].derCert =                                                                certificateInfo.derCert;                                certificatesList[certificatesNumber].keyId =                                                                certificateInfo.keyId;                                strncpy(certificatesList[certificatesNumber].keyHash,                                        certificateInfo.keyHash, 129);                                strncpy(certificatesList[certificatesNumber].tokenLabel,                                        certificateInfo.tokenLabel, 33);                                certificatesList[certificatesNumber].label=                                                                certificateInfo.label;                                certificatesList[certificatesNumber].certLen=                                                                certificateInfo.certLen;                                certificatesNumber++;                            }                            else                            {                                rv = p11->C_CloseSession(hSession);                            }                        }                    }                }            }        }        /**   - Next slot.*/        slotIndex++; /* Forward to the next slot.*/    }    return certificatesNumber;}/** \brief test if the certificate's key could be used for a specification. *   *  A cryptographic context is acquired with a container name precising the *  same key for signature and key exchange. *  Each key are next loaded. *  If the keys are loaded that means they could be used. *   *   *  \todo Do more serious test, with at least one querying for PIN. *   *  \param certificateInfo The certificate information structure. * *  \return -1: Error ! *           0: If neither AT_SIGNATURE neither AT_KEYEXCHANGE. *           1: If AT_SIGNATURE *           2: If AT_KEYEXCHANGE *           3: If AT_SIGNATURE & AT_KEYEXCHANGE */int certKeyCouldBe(CERTIFICATE_INFO certificateInfo){    int usage = 0; /* The returned usage integer. */    char cName[MAX_PATH]; /* The constructed cName.*/    HCRYPTPROV hProv = 0; /* The cryptographic context handle.*/    HCRYPTKEY hKey = 0; /* The cryptographic key handle.*/        /** - Construct the container name:     *    token label-sig key ID-\     *    sig key hash lbl-sig key hash-\     *    kx key ID-kx key hash lbl-kx key hash     *    */    sprintf(cName, "%s-%x-SHA1-%s-%x-SHA1-%s",certificateInfo.tokenLabel,                    certificateInfo.keyId, certificateInfo.keyHash,                    certificateInfo.keyId, certificateInfo.keyHash);    /*printf("Constructed: %s\n", cName);*/    if(!CryptAcquireContext(&hProv, cName,"CSP Eleven", 900,        CRYPT_SILENT))    {        usage = -1;    }    if((usage>=0) && CryptGetUserKey(hProv, AT_SIGNATURE, &hKey))    {        usage+=1;        if(!CryptDestroyKey(hKey))        {            usage = -1;        }    }    if((usage>=0) && CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hKey))    {        usage+=2;        if(!CryptDestroyKey(hKey))        {            usage = -1;        }    }    if(!CryptReleaseContext(hProv, 0))    {        return -1;    }    return usage;}/** \brief Main window procedure. *   */LRESULT WINAPI MainWndProc( HWND, UINT, WPARAM, LPARAM );/** \brief Test functions launcher.*/int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hInstPrevious, LPSTR c, int d){    WNDCLASS wc;        /* The window strucutre.*/    MSG msg;            /* The recieved windows message.*/    int i,j; /*Iterator*/    int keyUsage; /* Key usage.*/    HWND hLnd; /* Handle to the scroll list.*/    int certificatesNumber; /* Number of founded correct certificates.*/    CERTIFICATE_KEY_SPEC *certKeySpec;    char *listLabel;/* The list certificate label.*/    const char *keyXPrefix = "KEYX: ";    const char *sigPrefix = "SIGN: ";    char *label;    listLabel = NULL;    certKeySpec = NULL;    label = NULL;     module = hInstance;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -