当前位置: 首页 > 知识库问答 >
问题:

在Windows 10中编译的问题

孟选
2023-03-14

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

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);
            }
        }
    }
}

我已经有几个人在这里复制了它,我想在联系微软之前得到更多的信息。

我想我的问题是:有人能证实这一点吗,或者如果证实了,他们破坏了向后兼容性?

共有1个答案

南门鸿雪
2023-03-14

不知何故,certenroll.dll上的接口实现在“香草”Windows 2008和Windows 2008 R2之间发生了变化。我想在一些Windows7版本中也是如此。要使其(中途)工作,您必须使用activator.createInstance(type.getTypeFromProgid( ) 实例化类;这将导致系统查找hklm:\software\classes\interface\中的引用,以获得适合您的类。

(此代码的一部分使用于https://stackoverflow.com/A/13806300/5243037)

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://stackoverflow.com/a/13806300/5243037 </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=MATESO,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 v6.0中,第二个参数的类型必须是“CX509PrivateKey”,而在具有CertenRoll.dll v10的Win10计算机上,它是IX509PrivateKey:

所以您会想:是的,只需将上面示例中的privateKey“强制转换”为Activator.CreateInstance上的CX509PrivateKey。这里的问题是,它会编译,但在vanilla Win2k8上它不会给你类(CX509...)而是接口(IX509...),因此强制转换失败并返回NULL。

我们已经解决了这个问题,方法是使用CertenRoll.dllV10在一台机器上的独立项目中编译certenrollment函数。它的编译很好,在Win2k8中也可以工作。在一个独立的项目中使用它是非常麻烦的,因为在我们的buildserver上使用CertenRoll.dll v6进行构建会失败。

 类似资料:
  • 我正在尝试使用Dagger2学习依赖注入。我已经创建了很少的自定义范围和限定符。我已经创建了一个应用程序组件,我想在其中注入某些全局依赖项,我还创建了一个活动组件,它将基于活动上下文返回某些实例。 现在,当我试图在活动中注入全局实例时,我得到了如下错误: ApplicationScope.kt 在注入活动类中使用的ActivityComponent.kt。 用于注入应用程序类的FireBaseCo

  • 问题内容: 我已经为Windows 64位从gomingw安装了Go 。但是,我找不到任何地方实际如何编译.go文件。这是直接从Go Wiki获得Windows支持链接的程序,但是所有教程都讨论了如何使用6g和gccgo等,而这些在我的Windows机器上都不起作用。实际上,我想做的是,将“ hello.go”放入src文件夹,转到src文件夹后,在命令提示符下运行命令“ 8g hello.go”

  • 我正在尝试在最新的intellij(community edition)中使用Java9: IntelliJ IDEA 2016.3 Build#IC-163.7743.44,2016年11月17日构建jre:1.8.0_112-release-408-b2 x86 jvm:OpenJDK服务器VM由JetBrains S.r.o. 有人知道如何解决这个问题吗?还是我应该等到他们发布另一个版本?

  • 在试图使用JDK9.0.1编译Maven项目时,我遇到了这个stacktrace,但没有给出太多解释: 带有maven-compiler-plugin 3.7.0的Maven 3.5.0 我正在执行mvn clean Install 不幸的是,源代码不是开源的,所以我不能随意分享 还没有module-info.Java文件,我只是尝试使用Java9编译一个项目 奇怪的是,如果我将源级别保留在1.8

  • 我正在皮尔逊我的编程实验室做一项学校作业,顺便说一句,这完全糟透了,我的程序没有输出。然而,在netbean上,我的应用程序是可靠的,编译并给出所需的输出。我浏览了论坛,发现了一个类似的问题,但修复建议对我的应用程序不起作用。 以下是作业: 设计一个名为Person的类,其中包含用于保存人名、地址和电话号码的字段(全部作为字符串)。编写一个构造函数来初始化所有这些值,以及每个字段的mutator和

  • 我试图使用scalapb从protobuf生成case类。但是,我目前编译错误。 我有我的scalapb。sbt如下: 还有,我的构建。sbt如下: 此外,我还创建了一个示例。原型文件如下: 现在,当我尝试时,我收到以下错误: 有人能帮我解决这个错误吗? 我对scalapb的版本也有点困惑。萨米特。scalapb(https://scalapb.github.io/sbt-settings.htm