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

📄 createcert.c

📁 使用windows csp 簽發2048 bits 憑證
💻 C
📖 第 1 页 / 共 5 页
字号:
                          &dwSize,
                          NULL);
      if (!bResult)
      {
         printf("CertStrToName failed with %x\n", GetLastError());
         __leave;
      }

      // Allocate memory for Name Blob
      pbNameBlob = (LPBYTE)HeapAlloc(hHeap, 0, dwSize);
      if (!pbNameBlob)
      {
         printf("Unable to allocate memory for name blob\n");
         __leave;
      }

      // Convert X509 Name to Name Blob
      bResult = CertStrToName(X509_ASN_ENCODING,
                          szX509,
                          CERT_X500_NAME_STR,
                          NULL,
                          (LPBYTE)pbNameBlob,
                          &dwSize,
                          NULL);
      if (!bResult)
      {
         printf("CertStrToName failed with %x\n", GetLastError());
         __leave;
      }

      IssuerName.cbData = dwSize;
      IssuerName.pbData = pbNameBlob;

      // Convert Enhanced Key usage number to
      // Enhanced Key Usage extension

      // Find Enhanced Key Usage extensions count
      for (m = 0; m < g_EnhKeyUsage.dwCount; m++)
      {
        if ((g_EnhKeyUsage.dwValue[m] & dwUsage) == g_EnhKeyUsage.dwValue[m])
        {
          CertEnhKeyUsage.cUsageIdentifier++;
        }
      }

      // If extensions exist continue
      if (CertEnhKeyUsage.cUsageIdentifier != 0)
      {
         // Allocate memory for Enhanced Key Usage array
         CertEnhKeyUsage.rgpszUsageIdentifier =
             (LPSTR *)HeapAlloc(hHeap, 0, CertEnhKeyUsage.cUsageIdentifier * sizeof(LPSTR));
         if (!CertEnhKeyUsage.rgpszUsageIdentifier)
         {
           printf("Unable to allocate memory for Enhanced Usage array\n");
           __leave;
         }

         // Initialize Enhanced Key Usage array to NULL
         for (m = 0; m < CertEnhKeyUsage.cUsageIdentifier; m++)
         {
           CertEnhKeyUsage.rgpszUsageIdentifier[m] = NULL;
         }

         // Add proper extension OID to array
         q = 0;
         for (m = 0; m < g_EnhKeyUsage.dwCount; m++)
         {
           if ((g_EnhKeyUsage.dwValue[m] & dwUsage) == g_EnhKeyUsage.dwValue[m])
           {
             CertEnhKeyUsage.rgpszUsageIdentifier[q++] = g_EnhKeyUsage.szUsage[m];
           }
         }
      }

      // Create Crypto Context

      {
         UUID Uuid;
         HCRYPTPROV hTemp;

         // Create Temporary Provider
         bResult = CryptAcquireContext(&hTemp,
                                       "temp000",
                                       MS_DEF_PROV,
                                       PROV_RSA_FULL,
                                       CRYPT_NEWKEYSET);
         if (!bResult)
         {
            // If Temporary Provider exists already,
            // open it
            if (GetLastError() == NTE_EXISTS)
            {
               bResult = CryptAcquireContext(&hTemp,
                                          "temp000",
                                          MS_DEF_PROV,
                                          PROV_RSA_FULL,
                                          0);
               if (!bResult)
               {
                  printf("Unable to get temporary provider handle\n");
                  __leave;
               }
            }
            else
            {
               printf("Unable to create temporary provider handle\n");
               __leave;
            }
         }

         // Place random data in Uuid
         // Could have used UuidCreate but it is not supported
         // under Win9x.
         bResult = CryptGenRandom(hTemp, sizeof(Uuid), (LPBYTE)&Uuid);
         if (!bResult)
         {
            printf("CryptGenRandom failed with %x\n", GetLastError());
            __leave;
         }

         // Close Provider handle
         CryptReleaseContext(hTemp, 0);

         // Delete Container
         CryptAcquireContext(&hTemp,
                           "temp000",
                           MS_DEF_PROV,
                           PROV_RSA_FULL,
                           CRYPT_DELETEKEYSET);

         // Create a random uuid
         /*Status = UuidCreate(&Uuid);
         if (Status != RPC_S_OK)
         {
            printf("Unable to create random container\n");
            __leave;
         }*/

         // convert random uuid to a string, we will use it as a container
         Status = UuidToString(&Uuid, &szContainer);
         if (Status != RPC_S_OK)
         {
            printf("Unable to convert uuid to string\n");
            __leave;
         }

         // Create new crypto context
         bResult = CryptAcquireContext(&hProv,
                            szContainer,
                            szProvider,
                            dwProviderType,
                            CRYPT_NEWKEYSET | dwAcquireFlags);
         if (!bResult)
         {
            printf("CryptAcquireContext failed with %x\n", GetLastError());
            __leave;
         }
      }

      // Generate Private/Public key pair
      // bResult = CryptGenKey(hProv, dwKeyType, CRYPT_EXPORTABLE, &hPubKey);
	  //hdy 0918
		bResult = CryptGenKey(hProv, dwKeyType, 0x08000000, &hPubKey);
      if (!bResult)
      {
         printf("CryptGenKey failed with %x\n", GetLastError());
         __leave;
      }

      // Zero CERT_INFO structure
      ZeroMemory(&CertInfo, sizeof(CertInfo));

      // Set Version of Certificate
      CertInfo.dwVersion = CERT_V3;

      // Create Random Serial Number
      bResult = CryptGenRandom(hProv, 8, SerialNumber);
      if (!bResult)
      {
         printf("CryptGenRandom failed with %x\n", GetLastError());
         __leave;
      }

      // Set Serial Number of Certificate
      CertInfo.SerialNumber.cbData = 8;
      CertInfo.SerialNumber.pbData = SerialNumber;

      // Set Signature Algorithm of Certificate
      CertInfo.SignatureAlgorithm.pszObjId = szSigAlg;

      // set NotBefore date
      GetSystemTime(&stTime);
      SystemTimeToFileTime(&stTime, &ftTime);
      CertInfo.NotBefore = ftTime;

      if (wMonths == 0)
      {
         if (bSelfSigned)
            wMonths = 24;
         else
            wMonths = 6;
      }

      //
      // Set After Date
      //
      stTime.wMonth += wMonths;
      if ((stTime.wMonth / 12) > 0)
      {
         stTime.wYear += (stTime.wMonth / 12);
         stTime.wMonth = (stTime.wMonth % 12);
      }

      SystemTimeToFileTime(&stTime, &ftTime);
      CertInfo.NotAfter = ftTime;

      // Get Public Key Info size
      bResult = CryptExportPublicKeyInfo(hProv, dwKeyType,
                                       X509_ASN_ENCODING, NULL, &dwSize);
      if (!bResult)
      {
         printf("CryptExportPublicKeyInfo failed with %x\n", GetLastError());
         __leave;
      }

      // Allocate memory for Public Key Info
      PublicKeyInfo = (PCERT_PUBLIC_KEY_INFO)HeapAlloc(hHeap, 0, dwSize);
      if (!PublicKeyInfo)
      {
         printf("Unable to allocate memory for public key info\n");
         __leave;
      }

      // Get Public Key Info
      bResult = CryptExportPublicKeyInfo(hProv, dwKeyType,
                                       X509_ASN_ENCODING,
                                       PublicKeyInfo, &dwSize);
      if (!bResult)
      {
         printf("CryptExportPublicKeyInfo failed with %x\n", GetLastError());
         __leave;
      }

      // Set Public Key info of Certificate
      CertInfo.SubjectPublicKeyInfo = *PublicKeyInfo;

      // Create Hash
      bResult = CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
      if (!bResult)
      {
         printf("CryptCreateHash failed with %x\n", GetLastError());
         __leave;
      }

      // Hash Public Key Info
      bResult = CryptHashData(hHash, (LPBYTE)PublicKeyInfo, dwSize, 0);
      if (!bResult)
      {
         printf("CryptHashData failed with %x\n", GetLastError());
         __leave;
      }

      // Get Size of Hash
      bResult = CryptGetHashParam(hHash, HP_HASHVAL, NULL, &dwSize, 0);
      if (!bResult)
      {
         printf("CryptGetHashParam failed with %x\n", GetLastError());
         __leave;
      }

      // Allocate Memory for Key Identifier (hash of Public Key info)
      pbKeyIdentifier = (LPBYTE)HeapAlloc(hHeap, 0, dwSize);
      if (!pbKeyIdentifier)
      {
         printf("Unable to allocate memory for Hashed Public key Info\n");
         __leave;
      }

      // Get Hash of Public Key Info
      bResult = CryptGetHashParam(hHash, HP_HASHVAL, pbKeyIdentifier, &dwSize, 0);
      if (!bResult)
      {
         printf("CryptGetHashParam failed with %x\n", GetLastError());
         __leave;
      }

      // We will use this to set the Key Identifier extension
      CertKeyIdentifier.cbData = dwSize;
      CertKeyIdentifier.pbData = pbKeyIdentifier;

      // Set Subject of Certificate
      CertInfo.Subject = IssuerName;

      // Set Issuer of Certificate
      if (bSelfSigned)
      {
         CertInfo.Issuer = IssuerName;
      }
      else
      {
         pIssuerCert = FindCertificate(szIssuerName, szIssuerStore,
                                       dwIssuerFlags, &KeyId,
                                       &hIssuerProv, &dwIssuerKeyType);
         if (!pIssuerCert)
         {
            printf("Unable to find Issuer Certificate\n");
            __leave;
         }

         CertInfo.Issuer = pIssuerCert->pCertInfo->Subject;
      }

      // Get Subject Key Identifier Extension size
      bResult = CryptEncodeObject(ENCODING,
                                  szOID_SUBJECT_KEY_IDENTIFIER,
                                  (LPVOID)&CertKeyIdentifier,
                                  NULL, &dwSize);
      if (!bResult)
      {
         printf("CryptEncodeObject failed with %x\n", GetLastError());
         __leave;
      }

      // Allocate Memory for Subject Key Identifier Blob
      SubjectKeyIdentifier = (LPBYTE)HeapAlloc(hHeap, 0, dwSize);
      if (!SubjectKeyIdentifier)
      {
         printf("Unable to allocate memory for Subject Key Identifier\n");
         __leave;
      }

      // Get Subject Key Identifier Extension
      bResult = CryptEncodeObject(ENCODING,
                                  szOID_SUBJECT_KEY_IDENTIFIER,
                                  (LPVOID)&CertKeyIdentifier,
                                  SubjectKeyIdentifier, &dwSize);
      if (!bResult)
      {
         printf("CryptEncodeObject failed with %x\n", GetLastError());
         __leave;
      }

      // Set Subject Key Identifier
      CertExtension[CertInfo.cExtension].pszObjId = szOID_SUBJECT_KEY_IDENTIFIER;
      CertExtension[CertInfo.cExtension].fCritical = FALSE;
      CertExtension[CertInfo.cExtension].Value.cbData = dwSize;
      CertExtension[CertInfo.cExtension].Value.pbData = SubjectKeyIdentifier;

      // Increase extension count
      CertInfo.cExtension++;

      // Set Key Usage according to Public Key Type
      ZeroMemory(&KeyUsage, sizeof(KeyUsage));
      KeyUsage.cbData = 1;
      KeyUsage.pbData = &ByteData;

      if (dwKeyType == AT_SIGNATURE)
      {
         ByteData = CERT_DIGITAL_SIGNATURE_KEY_USAGE|
                    CERT_NON_REPUDIATION_KEY_USAGE|
                    CERT_KEY_CERT_SIGN_KEY_USAGE |
                    CERT_CRL_SIGN_KEY_USAGE;
      }

      if (dwKeyType == AT_KEYEXCHANGE)
      {
         ByteData = CERT_DIGITAL_SIGNATURE_KEY_USAGE |
                    CERT_DATA_ENCIPHERMENT_KEY_USAGE|
                    CERT_KEY_ENCIPHERMENT_KEY_USAGE |
                    CERT_KEY_AGREEMENT_KEY_USAGE;
      }

      // Get Key Usage blob size
      bResult = CryptEncodeObject(ENCODING,
                                  X509_KEY_USAGE,
                                  (LPVOID)&KeyUsage,
                                  NULL, &dwSize);
      if (!bResult)
      {
         printf("CryptEncodeObject failed with %x\n", GetLastError());
         __leave;
      }

      // Allocate Memory for Key Usage Blob
      pbKeyUsage = (LPBYTE)HeapAlloc(hHeap, 0, dwSize);
      if (!pbKeyUsage)
      {
         printf("Unable to allocate memory for Subject Key Identifier\n");
         __leave;
      }

      // Get Key Usage Extension blob
      bResult = CryptEncodeObject(ENCODING,
                                  X509_KEY_USAGE,
                                  (LPVOID)&KeyUsage,

⌨️ 快捷键说明

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