生成的签名X.509客户端证书无效(没有证书链到其CA)

时间:2011-01-11 16:02:58

标签: c# x509certificate bouncycastle

我使用Bouncy Castle生成X.509客户端证书,并使用已知的CA进行唱歌。

首先,我从证书存储区读取CA证书,生成客户端证书,使用CA对其进行签名。对以下问题验证证书失败

  

无法将证书链构建到受信任的根颁发机构。

据我了解,这是由于证书与CA无关。

以下是代码示例:

public static X509Certificate2 GenerateCertificate(X509Certificate2 caCert, string certSubjectName)
{
    // Generate Certificate

    var cerKp = kpgen.GenerateKeyPair();

    var certName = new X509Name(true,certSubjectName); // subjectName = user
    var serialNo = BigInteger.ProbablePrime(120, new Random());

    X509V3CertificateGenerator gen2 = new X509V3CertificateGenerator();
    gen2.SetSerialNumber(serialNo);
    gen2.SetSubjectDN(certName);
    gen2.SetIssuerDN(new X509Name(true,caCert.Subject));
    gen2.SetNotAfter(DateTime.Now.AddDays(100));
    gen2.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
    gen2.SetSignatureAlgorithm("SHA1WithRSA");
    gen2.SetPublicKey(cerKp.Public);


    AsymmetricCipherKeyPair akp = DotNetUtilities.GetKeyPair(caCert.PrivateKey);
    Org.BouncyCastle.X509.X509Certificate newCert = gen2.Generate(caKp.Private);

    // used for getting a private key
    X509Certificate2 userCert = ConvertToWindows(newCert,cerKp);

    if (caCert22.Verify()) // works well for CA 
    {
        if (userCert.Verify()) // fails for client certificate 
        {
            return userCert;
        }
    }
    return null;

}



private static X509Certificate2 ConvertToWindows(Org.BouncyCastle.X509.X509Certificate newCert, AsymmetricCipherKeyPair kp)
{
    string tempStorePwd = "abcd1234";
    var tempStoreFile = new FileInfo(Path.GetTempFileName());

    try
    {
        // store key 
        {
            var newStore = new Pkcs12Store();

            var certEntry = new X509CertificateEntry(newCert);

            newStore.SetCertificateEntry(
                newCert.SubjectDN.ToString(),
                certEntry
                );

            newStore.SetKeyEntry(
                newCert.SubjectDN.ToString(),
                new AsymmetricKeyEntry(kp.Private),
                new[] { certEntry }
                );
            using (var s = tempStoreFile.Create())
            {
                newStore.Save(
                    s,
                    tempStorePwd.ToCharArray(),
                    new SecureRandom(new CryptoApiRandomGenerator())
                    );
            }
        }

        // reload key 
        return new X509Certificate2(tempStoreFile.FullName, tempStorePwd);
    }
    finally
    {
        tempStoreFile.Delete();
    }
}

1 个答案:

答案 0 :(得分:1)

我想出来了。如果您调用X509Certificate.Verify(publicKey),则必须传递CA的公钥,而不是Pkcs10CertificationRequest中的客户端公钥。