在Windows 10中编译问题

16

我发现了一个与使用 C:\Windows\System32\CertEnroll.dll 作为引用构建应用程序相关的问题。

下面的代码在使用 VS 2015 在 Windows 7 上编译后,在 Windows 7 机器上运行时可以正常工作。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CERTENROLLLib;

namespace CertTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                CX509PrivateKey key = new CX509PrivateKey();
                key.ContainerName = Guid.NewGuid().ToString();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

当您在Windows 10上尝试编译它,然后尝试在Windows 7机器上运行时,会抛出以下错误:

"无法将类型为'System.__ComObject'的COM对象强制转换为接口类型'CERTENROLLLib.CX509PrivateKey'。 这个操作失败是因为在IID为'{728AB362-217D-11DA-B2A4-000E7BBB2B09}'的接口上对COM组件进行QueryInterface调用失败,由于以下错误:没有支持此类接口(HRESULT来自异常代码:0x80004002(E_NOINTERFACE))。

我们这里已有多人重现了此错误,我想在联系Microsoft询问情况之前获得更多意见。

我的问题是:有人能否证实这个问题或者确认他们破坏了向后兼容性?


你尝试过在64位和32位模式下运行吗?看起来微软在两者之间显着改变了接口。 - Ron Beyer
到目前为止,我的测试只在x64上进行过。 - spowser
1
从提升的命令提示符中,您可以运行 regsvr32 c:\Windows\System32\CertEnroll.dll 并查看是否有任何差异吗?这可能是由于注册表损坏引起的,否则请尝试在32位下运行并查看是否会出现相同的错误。 - Ron Beyer
.dll已成功注册。目标机器将始终为x64,此应用程序必须编译为x64。代码只是该应用程序的片段。如果我不得不猜测,这个问题与Windows 10中所做的ActiveX更改有关,但我认为那些只是针对Edge的。 - spowser
我可以确认我也遇到了同样的问题,你找到解决方案了吗? - zaitsman
显示剩余2条评论
3个回答

16
一些 Windows 2008 和 Windows 2008 R2 "原始" 版本与 CertEnroll.dll 上的接口实现方式发生了变化。我猜这也同样适用于某些 Windows 7 版本。为了让它(部分)正常运行,你需要使用 Activator.CreateInstance(Type.GetTypeFromProgID(<TypeName>) 实例化类;这将导致系统查找 HKLM:\SOFTWARE\Classes\Interface\ 中的引用以获取正确的类。
工作示例:
(此代码的一部分使用自https://dev59.com/XWYr5IYBdhLWcg3wRoSW#13806300)。
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using CERTENROLLLib;


/// <summary>
///     Creates a self-signed certificate in the computer certificate store MY.
///     Issuer and Subject are computername and its domain.
/// </summary>
/// <param name="friendlyName">Friendly-name of the certificate</param>
/// <param name="password">Password which will be used by creation. I think it's obsolete...</param>
/// <returns>Created certificate</returns>
/// <remarks>Base from https://dev59.com/XWYr5IYBdhLWcg3wRoSW#13806300 </remarks>
public static X509Certificate2 CreateSelfSignedCertificate(string friendlyName, string password)
{
    // create DN for subject and issuer
    var dnHostName = new CX500DistinguishedName();
    // DN will be in format CN=machinename, DC=domain, DC=local for machinename.domain.local
    dnHostName.Encode(GetMachineDn());
    var dnSubjectName = dnHostName;

    //var privateKey = new CX509PrivateKey();
    var typeName = "X509Enrollment.CX509PrivateKey";
    var type = Type.GetTypeFromProgID(typeName);
    if (type == null)
    {
        throw new Exception(typeName + " is not available on your system: 0x80040154 (REGDB_E_CLASSNOTREG)");
    }
    var privateKey = Activator.CreateInstance(type) as IX509PrivateKey;
    if (privateKey == null)
    {
        throw new Exception("Your certlib does not know an implementation of " + typeName +
                            " (in HKLM:\\SOFTWARE\\Classes\\Interface\\)!");
    }
    privateKey.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider";
    privateKey.ProviderType = X509ProviderType.XCN_PROV_RSA_AES;
    // key-bitness
    privateKey.Length = 2048;
    privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
    privateKey.MachineContext = true;
    // Don't allow export of private key
    privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_NONE;

    // use is not limited
    privateKey.Create();

    // Use the stronger SHA512 hashing algorithm
    var hashobj = new CObjectId();
    hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
        ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
        AlgorithmFlags.AlgorithmFlagsNone, "SHA512");

    // add extended key usage if you want - look at MSDN for a list of possible OIDs
    var oid = new CObjectId();
    oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server
    var oidlist = new CObjectIds { oid };
    var eku = new CX509ExtensionEnhancedKeyUsage();
    eku.InitializeEncode(oidlist);

    // add all IPs of current machine as dns-names (SAN), so a user connecting to our wcf 
    // service by IP still claim-trusts this server certificate
    var objExtensionAlternativeNames = new CX509ExtensionAlternativeNames();
    {
        var altNames = new CAlternativeNames();
        var dnsHostname = new CAlternativeName();
        dnsHostname.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, Environment.MachineName);
        altNames.Add(dnsHostname);
        foreach (var ipAddress in Dns.GetHostAddresses(Dns.GetHostName()))
        {
            if ((ipAddress.AddressFamily == AddressFamily.InterNetwork ||
                 ipAddress.AddressFamily == AddressFamily.InterNetworkV6) && !IPAddress.IsLoopback(ipAddress))
            {
                var dns = new CAlternativeName();
                dns.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, ipAddress.ToString());
                altNames.Add(dns);
            }
        }
        objExtensionAlternativeNames.InitializeEncode(altNames);
    }

    // Create the self signing request
    //var cert = new CX509CertificateRequestCertificate();
    typeName = "X509Enrollment.CX509CertificateRequestCertificate";
    type = Type.GetTypeFromProgID(typeName);
    if (type == null)
    {
        throw new Exception(typeName + " is not available on your system: 0x80040154 (REGDB_E_CLASSNOTREG)");
    }
    var cert = Activator.CreateInstance(type) as IX509CertificateRequestCertificate;
    if (cert == null)
    {
        throw new Exception("Your certlib does not know an implementation of " + typeName +
                            " (in HKLM:\\SOFTWARE\\Classes\\Interface\\)!");
    }
    cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, "");
    cert.Subject = dnSubjectName;
    cert.Issuer = dnHostName; // the issuer and the subject are the same
    cert.NotBefore = DateTime.Now.AddDays(-1);
    // this cert expires immediately. Change to whatever makes sense for you
    cert.NotAfter = DateTime.Now.AddYears(1);
    cert.X509Extensions.Add((CX509Extension)eku); // add the EKU
    cert.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames);
    cert.HashAlgorithm = hashobj; // Specify the hashing algorithm
    cert.Encode(); // encode the certificate

    // Do the final enrollment process
    //var enroll = new CX509Enrollment();
    typeName = "X509Enrollment.CX509Enrollment";
    type = Type.GetTypeFromProgID(typeName);
    if (type == null)
    {
        throw new Exception(typeName + " is not available on your system: 0x80040154 (REGDB_E_CLASSNOTREG)");
    }
    var enroll = Activator.CreateInstance(type) as IX509Enrollment;
    if (enroll == null)
    {
        throw new Exception("Your certlib does not know an implementation of " + typeName +
                            " (in HKLM:\\SOFTWARE\\Classes\\Interface\\)!");
    }
    // Use private key to initialize the certrequest...
    enroll.InitializeFromRequest(cert);
    enroll.CertificateFriendlyName = friendlyName; // Optional: add a friendly name
    var csr = enroll.CreateRequest(); // Output the request in base64 and install it back as the response
    enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr,
        EncodingType.XCN_CRYPT_STRING_BASE64, password);

    // This will fail on Win2k8, some strange "Parameter is empty" error... Thus we search the
    // certificate by serial number with the managed X509Store-class
    // // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
    //var base64Encoded = enroll.CreatePFX(password, PFXExportOptions.PFXExportChainNoRoot, EncodingType.XCN_CRYPT_STRING_BASE64);
    //return new X509Certificate2(Convert.FromBase64String(base64Encoded), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
    var certFs = LoadCertFromStore(cert.SerialNumber);
    if (!certFs.HasPrivateKey) throw new InvalidOperationException("Created certificate has no private key!");

    return certFs;
}


/// <summary>
///     Converts Domain.local into CN=Domain, CN=local
/// </summary>
private static string GetDomainDn()
{
    var fqdnDomain = IPGlobalProperties.GetIPGlobalProperties().DomainName;
    if (string.IsNullOrWhiteSpace(fqdnDomain)) return null;
    var context = new DirectoryContext(DirectoryContextType.Domain, fqdnDomain);
    var d = Domain.GetDomain(context);
    var de = d.GetDirectoryEntry();
    return de.Properties["DistinguishedName"].Value.ToString();
}

/// <summary>
///     Gets machine and domain name in X.500-format: CN=PC,DN=YourFirm,DN=local
/// </summary>
private static string GetMachineDn()
{
    var machine = "CN=" + Environment.MachineName;
    var dom = GetDomainDn();
    return machine + (string.IsNullOrWhiteSpace(dom) ? "" : ", " + dom);
}

/// <summary>
///     Load a certificate by serial number from computer.my-store
/// </summary>
/// <param name="serialNumber">Base64-encoded certificate serial number</param>
private static X509Certificate2 LoadCertFromStore(string serialNumber)
{
    var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    store.Open(OpenFlags.OpenExistingOnly | OpenFlags.MaxAllowed);
    try
    {
        // serialnumber from certenroll.dll v6 is a base64 encoded byte array, which is reversed.
        // serialnumber from certenroll.dll v10 is a base64 encoded byte array, which is NOT reversed.
        var serialBytes = Convert.FromBase64String(serialNumber);
        var serial = BitConverter.ToString(serialBytes.ToArray()).Replace("-", "");
        var serialReversed = BitConverter.ToString(serialBytes.Reverse().ToArray()).Replace("-", "");

        var serverCerts = store.Certificates.Find(X509FindType.FindBySerialNumber, serial, false);
        if (serverCerts.Count == 0)
        {
            serverCerts = store.Certificates.Find(X509FindType.FindBySerialNumber, serialReversed, false);
        }
        if (serverCerts.Count == 0)
        {
            throw new KeyNotFoundException("No certificate with serial number <" + serial + "> or reversed serial <" + serialReversed + "> found!");
        }
        if (serverCerts.Count > 1)
        {
            throw new Exception("Found multiple certificates with serial <" + serial + "> or reversed serial <" + serialReversed + ">!");
        }

        return serverCerts[0];
    }
    finally
    {
        store.Close();
    }
}

备注

为什么我说是“半途而废”呢?这是因为 certenroll.dll V. 6 存在问题,在 cert.InitializeFromPrivateKey 上构建会失败。在 certenroll.dll V 6.0 中,第二个参数必须是“CX509PrivateKey”类型,而在安装了Certenroll.dll V 10的Win10机器上,则是 IX509PrivateKey 类型:

error CS1503: Argument 2: cannot convert from 'CERTENROLLLib.IX509PrivateKey' to 'CERTENROLLLib.CX509PrivateKey'

你可能会想,那么简单啊,只要在 Activator.CreateInstance 中将 privateKey 强制转换为 CX509PrivateKey 就好了。但问题是,它会编译通过,但在普通 Win2k8 中不会给你类 (CX509...),而是接口 (IX509...),因此转换失败并返回 null。

我们通过在安装了 certenroll.dll V 10 的机器上编译 certenrollment 函数来解决这个问题。它能够在 Win2k8 上编译成功并正常工作。尽管如此,将其置于一个单独的项目中有点麻烦,因为如果使用 certenroll.dll V 6,就会在我们的构建服务器上构建失败。


GetMachineDN来自哪里? - Asher Garland

9
这是微软解决此问题的步骤:
如果您只在 Windows 10 上使用构建环境,那么可执行文件将在更早版本的操作系统上运行,但是,如果您真的只想创建一个可以在任何地方编译和运行的项目,则唯一的解决方案是创建自己的Interop DLL并将其包含在项目文件夹中。 您需要首先在Windows 7上生成它并引用该DLL。
Tlbimp.exe CertEnroll_Interop c:\Windows\System32\CertEnroll.dll
这将生成一个CertEnroll_Interop.dll文件,您可以将其复制到项目文件夹中,然后在项目中浏览到该文件。 当然,您还需要使用“using CertEnroll_Interop;”语句。
您可以在 Windows 10 上构建项目,并在 Windows 7、Windows 8.1 和其他任何组合上运行该项目。

注意:您需要使用/out开关,即 Tlbimp.exe /out:CertEnroll_Interop c:\Windows\System32\CertEnroll.dll否则它会认为CertEnroll_Interop是类型库名称,并抱怨找不到它。 - Tom Mulgrew

2

我曾经遇到过同样的问题,我的开发机运行在Windows 10上,而构建服务器则是Windows 8.1。

但是由于C#具有反射和动态类型的能力,现在我首先分析InitializeFromPrivateKey方法需要哪些类型作为参数(我通过创建一个方法将其与实际证书代码分离)。

    private static bool IsCompiledOnWin10AndAbove()
    {
        var typeOfMethod = typeof(IX509CertificateRequestPkcs10);
        var methodType = typeOfMethod.GetMethod("InitializeFromPrivateKey", new Type[] { typeof(X509CertificateEnrollmentContext), typeof(CX509PrivateKey), typeof(string) });
        var methodeParameters = methodType.GetParameters();
        return methodeParameters[1].ParameterType != typeof(CX509PrivateKey);
    }

然后根据第二个参数的类型使用动态类型。

        dynamic privateKeyCorrectType;
        if (IsCompiledOnWin10AndAbove()) // win 10 and above compiled
        {
            privateKeyCorrectType= privateKey;
        }
        else // below win 10 compiled
        {
            privateKeyCorrectType= (CX509PrivateKey)privateKey;
        }
        cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKeyCorrectType, "");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接