如何建立在我的计算机上有效的自我认证的x509证书

时间:2019-02-07 09:50:53

标签: c# .net x509certificate x509 x509certificate2

我需要构建一个自签名的x509证书,该证书通过C#代码在我的计算机上被识别为有效。

如果需要,可以使用管理员权限运行。

我当前的代码如下

public static X509Certificate2 GenerateCertificate(string name)
{
    string subjectName = $"CN={name}";
    using (RSA rsa = RSA.Create(2048))
    {
        CertificateRequest req = new CertificateRequest(
            subjectName,
            rsa,
            HashAlgorithmName.SHA256,
            RSASignaturePadding.Pkcs1);

        req.CertificateExtensions.Add(
            new X509BasicConstraintsExtension(false, false, 0, false));

        req.CertificateExtensions.Add(
            new X509KeyUsageExtension(
                X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.NonRepudiation,
                false));

        req.CertificateExtensions.Add(
            new X509EnhancedKeyUsageExtension(
                new OidCollection
                {
                    new Oid("1.3.6.1.5.5.7.3.8")
                },
                true));

        req.CertificateExtensions.Add(
            new X509SubjectKeyIdentifierExtension(req.PublicKey, false));

        return req.CreateSelfSigned(
            DateTimeOffset.UtcNow.AddDays(-1),
            DateTimeOffset.UtcNow.AddYears(50));
    }
}

public static X509Certificate2 GetOrCreateCertificate(string serverName)
{
    using (X509Store store = new X509Store(StoreLocation.LocalMachine))
    {
        X509Certificate2 certificate;
        store.Open(OpenFlags.ReadWrite);
        X509Certificate2Collection certificateCollection = store.Certificates.Find(X509FindType.FindBySubjectName, serverName, true);//With true, my certificates are not returned
        if (certificateCollection.Count > 0)
        {
            certificate = certificateCollection[0];
            return certificate;
        }

        certificate = GenerateCertificate(serverName);
        store.Add(certificate);

        return certificate;
    }
}

当前,如果我进入Windows MMC,证书管理单元,则可以看到证书,但该证书被视为无效。

我想念什么?

编辑

1 个答案:

答案 0 :(得分:1)

您遇到的问题似乎是系统不信任新证书。

为了得到信任,证书链的根必须在以下存储之一中表示:

  • LocalMachine \ Root
  • LocalMachine \ ThirdPartyRoot
  • CurrentUser \ Root

(还有其他一些商店,用于域管理的根权限)

所以做完之后

Set<String> namesInList2 = list2.stream().map(ObjectClass::getName).collect(toSet());
list1.removeIf(o -> namesInList2.contains(o.getName());

您也想做

certificate = GenerateCertificate(serverName);
store.Add(certificate);

现在,系统将能够验证(单节点)链到受信任的证书,并且Find上的using (X509Store rootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) using (X509Certificate2 withoutPrivateKey = new X509Certificate2(certificate.RawData)) { rootStore.Open(OpenFlags.ReadWrite); rootStore.Add(withoutPrivateKey); } 约束将认为证书是“有效的”(对于该方法,表示受链信任且未过期)。