CertEnroll :: CX509Enrollment :: InstallResponse: Не удается найти объект или свойство. 0x80092004 (-2146885628) - PullRequest
3 голосов
/ 06 июля 2011

У меня есть эта проблема, я написал код C # для

1.Генерация CSR программно 2. Отправьте CSR в Microsoft Certificate Services 3. Получите сертификат и сохраните как pfx.

Код работает отлично, но вместо создания CSR программно, когда я использую созданный CSRиспользуя IIS, я получаю вышеуказанную ошибку.

В чем может быть причина, пожалуйста?

Я могу создать сертификат в службах сертификации Microsoft (вызвав CCertRequestClass.Submit метод и может видеть его в выданных сертификатах),

, но я не могу установить его, возникает ошибка, когда я вызываю CX509EnrollmentClass.InstallResponse.Ниже мой код генерации CSR

     private static CCspInformations CreateCSP()
    {
        CCspInformation csp = new CCspInformationClass();
        CCspInformations csps = new CCspInformationsClass();

        string cspAlgorithmName = "Microsoft Enhanced Cryptographic Provider v1.0";

        //  Initialize the csp object using the desired Cryptograhic Service Provider (CSP)
        csp.InitializeFromName(cspAlgorithmName);

        //  Add this CSP object to the CSP collection object
        csps.Add(csp);

        return csps;
    }

    private static CX509PrivateKey CreatePrivateKey(CCspInformations csps)
    {
        CX509PrivateKey csrPrivateKey = new CX509PrivateKeyClass();

        //  Provide key container name, key length and key spec to the private key object
        csrPrivateKey.Length = 1024;
        csrPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
        csrPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE;
        csrPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
        csrPrivateKey.MachineContext = false;

        //  Provide the CSP collection object (in this case containing only 1 CSP object)
        //  to the private key object
        csrPrivateKey.CspInformations = csps;

        //  Create the actual key pair
        csrPrivateKey.Create();

        return csrPrivateKey;

    }

    private static CX509ExtensionKeyUsage CreateExtensionKeyUsage()
    {
        CX509ExtensionKeyUsage extensionKeyUsage = new CX509ExtensionKeyUsageClass();

        // Key Usage Extension 
        extensionKeyUsage.InitializeEncode(
            CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE |
            CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE |
            CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE |
            CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE
        );

        return extensionKeyUsage;
    }

    private static CX509ExtensionEnhancedKeyUsage CreateExtensionEnhancedKeyUsage()
    {
        CObjectIds objectIds = new CObjectIdsClass();
        CObjectId objectId = new CObjectIdClass();
        CX509ExtensionEnhancedKeyUsage extensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsageClass();

        string clientAuthOid = "1.3.6.1.5.5.7.3.2";
        string serverAuthOid = "1.3.6.1.5.5.7.3.1";

        // Enhanced Key Usage Extension
        objectId.InitializeFromValue(clientAuthOid); // OID for Client Authentication usage
        objectIds.Add(objectId);
        extensionEnhancedKeyUsage.InitializeEncode(objectIds);

        return extensionEnhancedKeyUsage;
    }

    private static CX500DistinguishedName CreateDN(string subject)
    {
        CX500DistinguishedName distinguishedName = new CX500DistinguishedNameClass();

        if (String.IsNullOrEmpty(subject))
        {
            subject = "CN=Suresh,C=IN,L=Bangalore,O=McAfee,OU=EMM,S=Karnataka";
        }

        //  Encode the name in using the Distinguished Name object
        distinguishedName.Encode(subject, X500NameFlags.XCN_CERT_NAME_STR_NONE);

        return distinguishedName;
    }

    /// <summary>
    /// Creates CSR
    /// </summary>
    /// <returns></returns>
    public static string CreateRequest()
    {
        CX509CertificateRequestPkcs10 pkcs10Request = new CX509CertificateRequestPkcs10Class();
        CX509Enrollment certEnroll = new CX509EnrollmentClass();

        //  Initialize the PKCS#10 certificate request object based on the private key.
        //  Using the context, indicate that this is a user certificate request and don't
        //  provide a template name
        pkcs10Request.InitializeFromPrivateKey(
            X509CertificateEnrollmentContext.ContextUser,
            CreatePrivateKey(CreateCSP()),
            string.Empty
        );

        pkcs10Request.X509Extensions.Add((CX509Extension)CreateExtensionKeyUsage());
        pkcs10Request.X509Extensions.Add((CX509Extension)CreateExtensionEnhancedKeyUsage());

        //  Assing the subject name by using the Distinguished Name object initialized above
        pkcs10Request.Subject = CreateDN(null);

        // Create enrollment request
        certEnroll.InitializeFromRequest(pkcs10Request);

        return certEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);
    }

1 Ответ

2 голосов
/ 07 марта 2015

Я тоже сталкивался с такой же проблемой. Этот код будет работать, если вы замените CX509CertificateRequestPkcs10 на CX509CertificateRequestCertificate.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...