简体   繁体   English

在 C# 中使用 Bouncy Castle 签署 CSR

[英]Signing CSR using Bouncy Castle in C#

I have created root and intermediate certificates using Bouncy Castle in C# .我在C#中使用Bouncy Castle创建了根证书和中间证书。 Now I want to accept and sign CSR using the certificate.现在我想接受并使用证书签署CSR I am getting Java solutions everywhere.我到处都是 Java 解决方案。 I want to convert java code to C# but not getting exact documentation for C#.我想将 java 代码转换为 C# 但没有获得 C# 的确切文档。 Can somebody please help with this.有人可以帮忙吗?

Here is my solution:这是我的解决方案:

public string SignCSR(string str_csr, int validityInYears)
        {
            try
            {
                char[] characters = str_csr.Replace("-----BEGIN CERTIFICATE REQUEST-----", "").Replace("-----END CERTIFICATE REQUEST-----", "").ToCharArray();

                byte[] csrEncode = Convert.FromBase64CharArray(characters, 0, characters.Length);
                Pkcs10CertificationRequest pk10Holder = new Pkcs10CertificationRequest(csrEncode);

                bool verify = pk10Holder.Verify();
                if (verify == false)
                {
                    return constants.INVALIDCERTIFICATEREQUEST;
                }
                // Generating Random Numbers
                CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
                SecureRandom random = new SecureRandom(randomGenerator);

                X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

                // Serial Number
                BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
                certificateGenerator.SetSerialNumber(serialNumber);

                //Import intermediate certificate and get issuer details
                string pathToRootCert = Configuration["intermediatecertificatelocation"];
                string intermediateIssuer = rootBusinessLogic.ImportIssuerFromPem(pathToRootCert);

                // Issuer and Subject Name
                //X509Name issuerDN = new X509Name(issuerName);
                X509Name issuerDN = new X509Name(intermediateIssuer);  //issuer is intermediate certificate here whi will sign
                certificateGenerator.SetIssuerDN(issuerDN);
                certificateGenerator.SetSubjectDN(pk10Holder.GetCertificationRequestInfo().Subject);

                // Valid For
                DateTime notBefore = DateTime.UtcNow.Date;
                DateTime notAfter = notBefore.AddYears(validityInYears);

                certificateGenerator.SetNotBefore(notBefore);
                certificateGenerator.SetNotAfter(notAfter);

                certificateGenerator.SetPublicKey(pk10Holder.GetPublicKey());


                //Import root certificate and get issuer details
                //get root private key from file
                string rootKeyPathFromConfig = Configuration["intermediate_privatekeylocation"];
                AsymmetricKeyParameter issuerPrivKey = rootBusinessLogic.ImportPrivateKeyFromPemFile(rootKeyPathFromConfig);
                if (issuerPrivKey == null)
                {
                    return constants.INTERMEDIATEKEYERROR;
                }

                ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivKey, random);

                // Selfsign certificate
                Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

                X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded());
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("-----BEGIN CERTIFICATE-----");
                builder.AppendLine(Convert.ToBase64String(x509.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
                builder.AppendLine("-----END CERTIFICATE-----");
                var str_certificate = builder.ToString();
                return str_certificate ;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
    }

pathToRootCert is the path to the intermediate certificate stored in the device, ImportIssuerFromPem is the method to retrieve issuer name of the intermediate certificate, rootKeyPathFromConfig is the path to the private key of intermediate certificate for signing purpose, ImportPrivateKeyFromPemFile is the method to get the private key in AsymmetricKeyParameter format. pathToRootCert是存储在设备中的中间证书的路径, ImportIssuerFromPem是获取中间证书颁发者名称的方法, ImportPrivateKeyFromPemFile rootKeyPathFromConfig获取私钥的方法采用AsymmetricKeyParameter格式。 This method returns certificate in PEM format.此方法返回 PEM 格式的证书。

I'm looking for (I think) a very similar solution - details here Using C# + BouncyCastle to sign a client certificate against my own CA .我正在寻找(我认为)一个非常相似的解决方案 - 详细信息在这里Using C# + BouncyCastle to sign a client certificate against my own CA

I was hoping your solution might have fixed my issue, but I still have problems getting the certificate to also include the CA.我希望您的解决方案可能解决了我的问题,但我仍然无法让证书也包含 CA。

If you can offer any suggestions I'd be very grateful!如果您能提供任何建议,我将不胜感激!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM