C# 通过PKCS#10证书申请,生成一个cer格式的设备证书

public static void NewCertificateFromRequest(string cert, out string strCert)//cert PKCS#10请求的内容
        {
            TextReader textReader = new StringReader(cert);
            PemReader pemReader = new PemReader(textReader);


            Pkcs10CertificationRequest certificationRequest = (Pkcs10CertificationRequest)pemReader.ReadObject();
            CertificationRequestInfo certificationRequestInfo = certificationRequest.GetCertificationRequestInfo();
            SubjectPublicKeyInfo publicKeyInfo = certificationRequestInfo.SubjectPublicKeyInfo;


            //RsaPublicKeyStructure publicKeyStructure = RsaPublicKeyStructure.GetInstance(publicKeyInfo.GetPublicKey());


            //RsaKeyParameters publicKey = new RsaKeyParameters(false, publicKeyStructure.Modulus, publicKeyStructure.PublicExponent);
            AsymmetricKeyParameter  publicKey = PublicKeyFactory.CreateKey(publicKeyInfo);
         
            bool certIsOK = certificationRequest.Verify(publicKey);
            // public key is OK here...


            // get the server certificate
            X509Certificate serverCertificate = DotNetUtilities.FromX509Certificate(new System.Security.Cryptography.X509Certificates.X509Certificate(Encoding.Default.GetBytes(RawCert(RootCert))));


            // get the server private key
            byte[] privateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(RootKey).ToAsn1Object().GetDerEncoded();
            AsymmetricKeyParameter serverPrivateKey = PrivateKeyFactory.CreateKey(privateKeyBytes);


            // generate the client certificate
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();


            generator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
            generator.SetIssuerDN(serverCertificate.SubjectDN);
            generator.SetNotBefore(DateTime.Now.AddDays(-1));
            generator.SetNotAfter(DateTime.Now.AddYears(2));
            generator.SetSubjectDN(certificationRequestInfo.Subject);
            generator.SetPublicKey(publicKey);
            generator.SetSignatureAlgorithm("SHA512withRSA");
            generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(serverCertificate));
            generator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey));


            var newClientCert = generator.Generate(serverPrivateKey);
            strCert = RawCert(newClientCert);
        }

你可能感兴趣的:(CA证书处理)