private void init(ISignatureFactory signatureCalculator, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes, AsymmetricKeyParameter signingKey)
    {
        sigAlgId = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
        SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

        reqInfo = new CertificationRequestInfo(subject, pkInfo, attributes);
        IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

        byte[] derEncoded = reqInfo.GetDerEncoded();
        streamCalculator.Stream.Write(derEncoded, 0, derEncoded.Length);
        Platform.Dispose(streamCalculator.Stream);
        sigBits = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
    }
Exemplo n.º 2
0
 internal PKCS10CertificationRequest(ASN1Sequence seq)
 {
     try
     {
         this.reqInfo  = CertificationRequestInfo.getInstance(seq.getObjectAt(0));
         this.sigAlgId = AlgorithmIdentifier.getInstance(seq.getObjectAt(1));
         this.sigBits  = (DERBitString)seq.getObjectAt(2);
     }
     catch (Exception ex)
     {
         throw new ArgumentException("Create From ASN1Sequence: " + ex.Message);
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Get the common name
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        private Identifier ParseCn(CertificationRequestInfo info)
        {
            var subject = info.Subject;
            var cnValue = subject.GetValueList(new DerObjectIdentifier("2.5.4.3"));

            if (cnValue.Count > 0)
            {
                var name = cnValue.Cast <string>().ElementAt(0);
                return(new DnsIdentifier(name).Unicode(true));
            }
            else
            {
                throw new Exception("Unable to parse common name");
            }
        }
    public Pkcs10CertificationRequestDelaySigned(string signatureAlgorithm, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes)
    {
        if (signatureAlgorithm == null)
        {
            throw new ArgumentNullException("signatureAlgorithm");
        }
        if (subject == null)
        {
            throw new ArgumentNullException("subject");
        }
        if (publicKey == null)
        {
            throw new ArgumentNullException("publicKey");
        }
        if (publicKey.IsPrivate)
        {
            throw new ArgumentException("expected public key", "publicKey");
        }
        string text = Platform.ToUpperInvariant(signatureAlgorithm);
        DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)Pkcs10CertificationRequest.algorithms[text];

        if (derObjectIdentifier == null)
        {
            try
            {
                derObjectIdentifier = new DerObjectIdentifier(text);
            }
            catch (Exception innerException)
            {
                throw new ArgumentException("Unknown signature type requested", innerException);
            }
        }
        if (Pkcs10CertificationRequest.noParams.Contains(derObjectIdentifier))
        {
            sigAlgId = new AlgorithmIdentifier(derObjectIdentifier);
        }
        else if (Pkcs10CertificationRequest.exParams.Contains(text))
        {
            sigAlgId = new AlgorithmIdentifier(derObjectIdentifier, (Asn1Encodable)Pkcs10CertificationRequest.exParams[text]);
        }
        else
        {
            sigAlgId = new AlgorithmIdentifier(derObjectIdentifier, DerNull.Instance);
        }
        SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

        reqInfo = new CertificationRequestInfo(subject, pkInfo, attributes);
    }
        /// <summary>
        /// Call to request a certificate
        /// </summary>
        /// <param name="csr">Certificate signing request</param>
        /// <param name="effectiveDate">Effective date of certificate</param>
        /// <param name="expirationDate">Expiration date of certificate</param>
        /// <param name="ca">Signing authority</param>
        /// <param name="asn1Set">Extensions</param>
        /// <exception cref="InvalidParameterException">Thrown if <paramref name="ca"/> is null</exception>
        /// <returns>Certificate signed by <paramref name="ca"/></returns>
        public static X509Certificate2 RequestCertificate(Pkcs10CertificationRequest csr, DateTime effectiveDate, DateTime expirationDate, X509Certificate2 ca, Asn1Set asn1Set)
        {
            AsymmetricKeyParameter keyParameter = null;

            if (ca == null)
            {
                throw new InvalidParameterException("ca can not be null");
            }

            keyParameter = TransformRSAPrivateKey((RSACryptoServiceProvider)ca.PrivateKey);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(CreateSerialNumber());
            certGen.SetIssuerDN(new X509Name(ca.Subject));
            certGen.SetNotBefore(effectiveDate.ToUniversalTime());
            certGen.SetNotAfter(expirationDate.ToUniversalTime());
            certGen.SetSubjectDN(csr.GetCertificationRequestInfo().Subject);
            certGen.SetPublicKey(csr.GetPublicKey());
            certGen.SetSignatureAlgorithm(SIGNATURE_ALGORITHM);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            if (asn1Set != null)
            {
                // Iterate through each extension and add it to the certificate
                for (int i = 0; i < asn1Set.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(asn1Set[i]);

                    if (attr != null && attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier extOid in extensions.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions.GetExtension(extOid);

                            certGen.AddExtension(extOid, ext.IsCritical, ext.GetParsedValue());
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(keyParameter);

            return(new X509Certificate2(bcCert.GetEncoded()));
        }
        /// <summary>
        /// Generate an PKCS#10 request based on the past in signer.
        /// </summary>
        /// <param name="signerFactory">the content signer to be used to generate the signature validating the certificate.</param>
        /// <returns>a holder containing the resulting PKCS#10 certification request.</returns>
        public Pkcs10CertificationRequest Build(
            ISignatureFactory <AlgorithmIdentifier> signerFactory)
        {
            CertificationRequestInfo info;

            if (attributes.Count == 0)
            {
                if (leaveOffEmpty)
                {
                    info = new CertificationRequestInfo(subject, publicKeyInfo, null);
                }
                else
                {
                    info = new CertificationRequestInfo(subject, publicKeyInfo, new DerSet());
                }
            }
            else
            {
                Asn1EncodableVector v = new Asn1EncodableVector();

                for (int i = 0; i != attributes.Count; i++)
                {
                    v.Add(AttributePkcs.GetInstance(attributes[i]));
                }

                info = new CertificationRequestInfo(subject, publicKeyInfo, new DerSet(v));
            }

            try
            {
                IStreamCalculator <IBlockResult> signer = signerFactory.CreateCalculator();

                Stream sOut = signer.Stream;

                byte[] data = info.GetEncoded(Asn1Encodable.Der);

                sOut.Write(data, 0, data.Length);

                sOut.Close();

                return(new Pkcs10CertificationRequest(new CertificationRequest(info, signerFactory.AlgorithmDetails, new DerBitString(signer.GetResult().Collect()))));
            }
            catch (IOException e)
            {
                throw new InvalidOperationException("cannot produce certification request signature: " + e.Message, e);
            }
        }
Exemplo n.º 7
0
        private byte[] gen()
        {
            TextReader textReader = new StreamReader("certificaterequest.pkcs10");
            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);

            bool certIsOK = certificationRequest.Verify(publicKey);

            // public key is OK here...

            // get the server certificate
            Org.BouncyCastle.X509.X509Certificate serverCertificate = DotNetUtilities.FromX509Certificate(System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile("servermastercertificate.cer"));

            // get the server private key
            byte[] privateKeyBytes = File.ReadAllBytes("serverprivate.key");

            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);
            generator.SetNotAfter(DateTime.Now.AddYears(5));
            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);

            newClientCert.Verify(publicKey); // <-- this blows up

            return(DotNetUtilities.ToX509Certificate(newClientCert).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, "user password"));
        }
        /// <summary>
        /// Generates client certificate by certificate signing request.
        /// </summary>
        /// <param name="csrBytes">CSR as bytes array</param>
        /// <param name="commonName">Common name of certificate</param>
        /// <exception cref="InvalidCastException">Invalid format of CSR</exception>
        /// <returns></returns>
        public static X509Certificate2 SignRequest(byte[] csrBytes, string commonName)
        {
            if (string.IsNullOrEmpty(commonName))
            {
                throw new ArgumentNullException("commonName");
            }

            var certificationRequest         = new Pkcs10CertificationRequest(csrBytes);
            CertificationRequestInfo csrInfo = certificationRequest.GetCertificationRequestInfo();
            SubjectPublicKeyInfo     pki     = csrInfo.SubjectPublicKeyInfo;

            AsymmetricKeyParameter publicKey = PublicKeyFactory.CreateKey(pki);

            // Version1 (No Extensions) Certificate
            DateTime startDate    = DateTime.UtcNow;
            DateTime expiryDate   = startDate.AddYears(100);
            var      serialNumber = new BigInteger(32, new Random());

            var certGen = new X509V1CertificateGenerator();
            var x509ServerCertificate = ServerCertificate;
            var caCert = DotNetUtilities.FromX509Certificate(x509ServerCertificate);

            certGen.SetSerialNumber(serialNumber);
            certGen.SetIssuerDN(caCert.SubjectDN);
            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(expiryDate);
            certGen.SetSubjectDN(CreateSubject(commonName));
            certGen.SetSignatureAlgorithm("SHA256withRSA");
            certGen.SetPublicKey(publicKey);

            var keyPath = string.Format(@"{0}\App_Data\server.key", AppDomain.CurrentDomain.BaseDirectory);

            AsymmetricCipherKeyPair keyPair;

            using (var reader = File.OpenText(keyPath))
            {
                keyPair = (AsymmetricCipherKeyPair) new PemReader(reader, new PasswordFinder()).ReadObject();
            }

            Org.BouncyCastle.X509.X509Certificate cert = certGen.Generate(keyPair.Private);

            return(new X509Certificate2(DotNetUtilities.ToX509Certificate(cert)));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Parse the SAN names.
        /// Based on https://stackoverflow.com/questions/44824897/getting-subject-alternate-names-with-pkcs10certificationrequest
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        private IEnumerable <Identifier> ParseSan(CertificationRequestInfo info)
        {
            var ret = new List <Identifier>();
            var extensionSequence = info.Attributes.OfType <DerSequence>()
                                    .Where(o => o.OfType <DerObjectIdentifier>().Any(oo => oo.Id == "1.2.840.113549.1.9.14"))
                                    .FirstOrDefault();

            if (extensionSequence == null)
            {
                return(ret);
            }
            var extensionSet = extensionSequence.OfType <DerSet>().FirstOrDefault();

            if (extensionSet == null)
            {
                return(ret);
            }
            var sequence = extensionSet.OfType <DerSequence>().FirstOrDefault();

            if (sequence == null)
            {
                return(ret);
            }
            var derOctetString = GetAsn1ObjectRecursive <DerOctetString>(sequence, "2.5.29.17");

            if (derOctetString == null)
            {
                return(ret);
            }
            var asn1object = Asn1Object.FromByteArray(derOctetString.GetOctets());
            var names      = Org.BouncyCastle.Asn1.X509.GeneralNames.GetInstance(asn1object);

            return(names.GetNames().Select(x => x.TagNo switch {
                1 => new EmailIdentifier(x.Name.ToString() !),
                2 => new DnsIdentifier(x.Name.ToString() !).Unicode(true),
                7 => new IpIdentifier(x.Name.ToString() !),
                _ => new UnknownIdentifier(x.Name.ToString() !)
            }));
        /// <summary>
        /// Sign a certificate
        /// </summary>
        /// <param name="signingCert">Issuer X509Certificate2</param>
        /// <param name="csrData">CSR Data</param>
        /// <returns>X509Certificate2 Certificate</returns>
        private X509Certificate2 SignCertificate(X509Certificate2 signingCert, byte[] csrData)
        {
            //Get CSR and retrieve public key
            Pkcs10CertificationRequest certRequest       = new Pkcs10CertificationRequest(csrData);
            CertificationRequestInfo   certInfo          = certRequest.GetCertificationRequestInfo();
            SubjectPublicKeyInfo       certPublicKeyInfo = certInfo.SubjectPublicKeyInfo;
            AsymmetricKeyParameter     certPublicKey     = PublicKeyFactory.CreateKey(certPublicKeyInfo);

            if (!certRequest.Verify(certPublicKey))
            {
                throw new ApplicationException("The CSR is not valid: verification failed");
            }

            //Get private key of intermediate issuer, to be used to sign the certificate
            var issuer = DotNetUtilities.FromX509Certificate(signingCert);
            AsymmetricCipherKeyPair keyPrivate = DotNetUtilities.GetRsaKeyPair(signingCert.GetRSAPrivateKey());
            //Get the serial number of the issuer
            var issuerSerialNumber = new BigInteger(signingCert.GetSerialNumber());

            //Generate a signed certificate
            return(GenerateCertificate(certInfo.Subject, certPublicKey, certPublicKeyInfo,
                                       issuer.SubjectDN, issuer.GetPublicKey(), keyPrivate.Private, issuerSerialNumber));
        }
Exemplo n.º 11
0
        private void readRequest(bool verify)
        {
            // Perform POP on the request
            if ((verify) && (!Request.Verify()))
            {
                throw new SignatureException("Invalid signature on PKCS#10 request");
            }

            // Contents
            info = Request.GetCertificationRequestInfo();

            // Attributes - if there are no attributes in the request then info.Attributes will be null and cause an
            // exception in the following foreach; attributes should be null if there aren't any.
            if (info.Attributes != null)
            {
                attributes = new Dictionary <DerObjectIdentifier, Asn1Set>();
                foreach (object entry in info.Attributes)
                {
                    AttributePkcs attrib = AttributePkcs.GetInstance(entry);
                    attributes.Add(attrib.AttrType, attrib.AttrValues);
                }
            }
            else
            {
                attributes = null;
            }

            // Extensions in OSCA format
            // Make sure there are some extensions first
            if (Extensions != null)
            {
                foreach (DerObjectIdentifier oid in Extensions.ExtensionOids)
                {
                    oscaExtensions.Add(ProfileExtensionFactory.GetExtension(oid, Extensions.GetExtension(oid)));
                }
            }
        }
Exemplo n.º 12
0
        private void readRequest()
        {
            // Perform POP on the request
            if (!request.Verify())
            {
                throw new SignatureException("Invalid signature on PKCS#10 request");
            }

            // Contents
            info = request.GetCertificationRequestInfo();

            // Extensions in OSCA format
            foreach (DerObjectIdentifier oid in Extensions.ExtensionOids)
            {
                oscaExtensions.Add(ProfileExtensionFactory.GetExtension(oid, Extensions.GetExtension(oid)));
            }

            // Attributes
            foreach (object entry in Attributes)
            {
                AttributePkcs attrib = AttributePkcs.GetInstance(entry);
                attributes.Add(attrib.AttrType, attrib.AttrValues);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        ///  get sm2 csr
        /// </summary>
        /// <param name="issuerName"></param>
        /// <returns></returns>
        public static Tuple <string, AsymmetricKeyParameter> GetSMCsr(string issuerName)
        {
            //generate KeyPair
            var keyGenerator             = new ECKeyPairGenerator();
            ECKeyGenerationParameters pa = new ECKeyGenerationParameters(GMObjectIdentifiers.sm2p256v1, new SecureRandom());

            keyGenerator.Init(pa);
            var keypair = keyGenerator.GenerateKeyPair();

            //domain name of CSR file
            X509Name principal = new X509Name(string.Format("CN={0},OU=client,O=BSN", string.IsNullOrEmpty(issuerName) ? "test02@app0001202004161020152918451" : issuerName));

            //load public key
            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public);

            CertificationRequestInfo info = new CertificationRequestInfo(principal, subjectPublicKeyInfo, new DerSet());

            //signature
            byte[] bs = SM2.SM2Utils.Sign(info.GetEncoded(Asn1Encodable.Der), keypair.Private);
            //ECDSAHelper.CsrSignData(info.GetEncoded(Asn1Encodable.Der), keypair.Private, pa.DomainParameters.N);
            //generate csr object
            Pkcs10CertificationRequest p10 = new Pkcs10CertificationRequest(new CertificationRequest
                                                                                (info, new AlgorithmIdentifier(GMObjectIdentifiers.sm2sign_with_sm3),
                                                                                new DerBitString(bs)).GetEncoded());

            //generate csr string
            Org.BouncyCastle.Utilities.IO.Pem.PemObject pemCSR = new Org.BouncyCastle.Utilities.IO.Pem.PemObject("CERTIFICATE REQUEST", p10.GetEncoded());

            StringWriter str = new StringWriter();

            Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemCsr = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(str);
            pemCsr.WriteObject(pemCSR);
            pemCsr.Writer.Flush();

            return(new Tuple <string, AsymmetricKeyParameter>(str.ToString(), keypair.Private));
        }
        public async Task ValidateMergeCertificate()
        {
            string serverCertificateName = Recording.GenerateId();

            // Generate the request.
            CertificatePolicy policy = new CertificatePolicy(WellKnownIssuerNames.Unknown, "CN=Azure SDK")
            {
                CertificateTransparency = false,
                ContentType             = CertificateContentType.Pkcs12,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(serverCertificateName, policy);

            RegisterForCleanup(serverCertificateName);
            await using IAsyncDisposable disposableOperation = EnsureDeleted(operation);

            // Read the CA.
            byte[]           caCertificateBytes = Convert.FromBase64String(CaPublicKeyBase64);
            X509Certificate2 caCertificate      = new X509Certificate2(caCertificateBytes);

            // Read CA private key since getting it from caCertificate above throws.
            AsymmetricCipherKeyPair caPrivateKey;

            using (StringReader caPrivateKeyReader = new StringReader(CaPrivateKeyPem))
            {
                Org.BouncyCastle.OpenSsl.PemReader reader = new Org.BouncyCastle.OpenSsl.PemReader(caPrivateKeyReader);
                caPrivateKey = (AsymmetricCipherKeyPair)reader.ReadObject();
            }

            // Read the CSR.
            Pkcs10CertificationRequest csr     = new Pkcs10CertificationRequest(operation.Properties.Csr);
            CertificationRequestInfo   csrInfo = csr.GetCertificationRequestInfo();

            // Parse the issuer subject name.
            Hashtable oidLookup = new Hashtable(X509Name.DefaultLookup)
            {
                { "s", new DerObjectIdentifier("2.5.4.8") },
            };

            X509Name issuerName = new X509Name(true, oidLookup, caCertificate.Subject);

            // Sign the request.
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetIssuerDN(issuerName);
            generator.SetSerialNumber(BigInteger.One);
            generator.SetNotBefore(DateTime.Now);
            generator.SetNotAfter(DateTime.Now.AddDays(1));
            generator.SetSubjectDN(csrInfo.Subject);
            generator.SetPublicKey(csr.GetPublicKey());

            Asn1SignatureFactory signatureFactory      = new Asn1SignatureFactory("SHA256WITHRSA", caPrivateKey.Private);
            X509Certificate      serverSignedPublicKey = generator.Generate(signatureFactory);

            // Merge the certificate chain.
            MergeCertificateOptions       options = new MergeCertificateOptions(serverCertificateName, new[] { serverSignedPublicKey.GetEncoded(), caCertificateBytes });
            KeyVaultCertificateWithPolicy mergedServerCertificate = await Client.MergeCertificateAsync(options);

            X509Certificate2 serverCertificate = new X509Certificate2(mergedServerCertificate.Cer);

            Assert.AreEqual(csrInfo.Subject.ToString(), serverCertificate.Subject);
            Assert.AreEqual(serverCertificateName, mergedServerCertificate.Name);

            KeyVaultCertificateWithPolicy completedServerCertificate = await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            Assert.AreEqual(mergedServerCertificate.Name, completedServerCertificate.Name);
            CollectionAssert.AreEqual(mergedServerCertificate.Cer, completedServerCertificate.Cer);
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                                  .AddCertificateManager()
                                  .BuildServiceProvider();

            var createCertificates = serviceProvider.GetService <CreateCertificates>();
            var certificateUtility = serviceProvider.GetService <CertificateUtility>();

            string password = "******";

            var signingCertificate = new X509Certificate2("root.cert.pfx", password);
            var enhancedKeyUsages  = new OidCollection {
                OidLookup.ClientAuthentication,
                OidLookup.ServerAuthentication
            };

            var basicConstraints = new CertificateManager.Models.BasicConstraints
            {
                CertificateAuthority    = false,
                HasPathLengthConstraint = true,
                PathLengthConstraint    = 3,
                Critical = true
            };

            var x509KeyUsageFlags = X509KeyUsageFlags.DigitalSignature
                                    | X509KeyUsageFlags.KeyEncipherment
                                    | X509KeyUsageFlags.NonRepudiation;

            // Read in CSR data from a file
            Pkcs10CertificationRequest decodedCsr = (Pkcs10CertificationRequest) new PemReader(new StringReader(File.ReadAllText(args[0]))).ReadObject();
            // Get Common Name (CN) from CSR Subject
            CertificationRequestInfo csrData = decodedCsr.GetCertificationRequestInfo();
            var subjectKeyPairs = csrData.Subject.ToString().Split(',')
                                  .Select(x => x.Split('='))
                                  .Where(x => x.Length == 2)
                                  .ToDictionary(x => x.First(), x => x.Last());
            var commonName             = subjectKeyPairs["CN"];
            var subjectAlternativeName = new SubjectAlternativeName
            {
                DnsName = new List <string>
                {
                    commonName,
                }
            };
            // Get Public key data from CSR and create RSA data based on that
            RsaKeyParameters rsaKeyParams = (RsaKeyParameters)decodedCsr.GetPublicKey();
            var rsaParams = new RSAParameters();

            rsaParams.Modulus  = rsaKeyParams.Modulus.ToByteArray();
            rsaParams.Exponent = rsaKeyParams.Exponent.ToByteArray();
            var rsa = RSA.Create();

            rsa.ImportParameters(rsaParams);

            // Create Certificate Request with the data extracted from csr file earlier
            var rsaConfiguration = new RsaConfiguration();
            var request          = new CertificateRequest(
                certificateUtility.CreateIssuerOrSubject(new DistinguishedName {
                CommonName = commonName
            }),
                rsa,
                rsaConfiguration.HashAlgorithmName,
                rsaConfiguration.RSASignaturePadding);

            // Sign the csr
            var device1Certificate = createCertificates.NewRsaChainedCertificate(
                basicConstraints,
                new ValidityPeriod {
                ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(1)
            },
                subjectAlternativeName,
                signingCertificate,
                enhancedKeyUsages,
                x509KeyUsageFlags,
                request,
                null);

            // Export content of certificates into files
            var importExportCertificate = serviceProvider.GetService <ImportExportCertificate>();
            var deviceCertificatePem    = importExportCertificate.PemExportPublicKeyCertificate(device1Certificate);
            var signingCertificatePem   = importExportCertificate.PemExportPublicKeyCertificate(signingCertificate);

            File.WriteAllText("device1.cert.pem", deviceCertificatePem);
            File.WriteAllText("device1-full-chain.cert.pem", String.Concat(deviceCertificatePem, signingCertificatePem));

            Console.WriteLine("Certificates exported to pem files");
        }
Exemplo n.º 16
0
        /// <summary>
        /// Enroll certificate file base on request
        /// </summary>
        /// <param name="cerRequest"></param>
        /// <param name="rootCert"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        private Org.BouncyCastle.X509.X509Certificate GenerateSignedCertificate(
            Pkcs10CertificationRequest cerRequest,
            Org.BouncyCastle.X509.X509Certificate rootCert,
            AsymmetricCipherKeyPair issuerKeyPair,
            DateTime startDate, DateTime endDate)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(rootCert.SubjectDN);
            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(endDate);

            CertificationRequestInfo info = cerRequest.GetCertificationRequestInfo();

            certGen.SetSubjectDN(info.Subject);

            certGen.SetPublicKey(cerRequest.GetPublicKey());

            AlgorithmIdentifier sigAlg = cerRequest.SignatureAlgorithm;
            string algName             = GetAlgorithmName(sigAlg.Algorithm.Id);

            certGen.SetSignatureAlgorithm(algName);

            // Add certificate extensions
            Asn1Set attributes = cerRequest.GetCertificationRequestInfo().Attributes;

            if (attributes != null)
            {
                for (int i = 0; i != attributes.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(attributes[i]);

                    if (attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions1 = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier oid in extensions1.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions1.GetExtension(oid);
                            certGen.AddExtension(oid, ext.IsCritical, ext.GetParsedValue());
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate issuedCert = null;
            try
            {
                issuedCert = certGen.Generate(issuerKeyPair.Private);
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Certificate file sucessfully generated." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error, generate certificate file." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            try
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Check if generated certificate file is valid, plase wait ..." + "\n",
                        Foreground = System.Windows.Media.Brushes.Black
                    });
                }));
                issuedCert.CheckValidity(DateTime.UtcNow);
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Generate certificate file is valid." + "\n",
                        Foreground = System.Windows.Media.Brushes.Black
                    });
                }));
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error, generated certificate file is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            try
            {
                tbOutputMessageBox.Inlines.Add(new Run
                {
                    Text       = "Verify generated certificate file, plase wait ..." + "\n",
                    Foreground = System.Windows.Media.Brushes.Black
                });
                issuedCert.Verify(issuerKeyPair.Public);
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Generate certificate file verification is OK." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error, generated certificate file verification is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }
            return(issuedCert);
        }
Exemplo n.º 17
0
 public CertificationRequest(CertificationRequestInfo requestInfo, AlgorithmIdentifier algorithm, DerBitString signature)
 {
     reqInfo  = requestInfo;
     sigAlgId = algorithm;
     sigBits  = signature;
 }
Exemplo n.º 18
0
        /// <summary>
        /// Enroll certificate file base on request
        /// </summary>
        /// <param name="csr"></param>
        /// <param name="rootCert"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        private Org.BouncyCastle.X509.X509Certificate GenerateSignedCertificate(
            Pkcs10CertificationRequest csr,
            Org.BouncyCastle.X509.X509Certificate rootCert,
            AsymmetricCipherKeyPair issuerKeyPair,
            DateTime startDate, DateTime endDate)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            //List<ExtensionsItem> extensions = null;

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(rootCert.SubjectDN);

            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(endDate);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            certGen.SetSubjectDN(info.Subject);

            certGen.SetPublicKey(csr.GetPublicKey());

            var sigAlg  = csr.Signature;
            var sigAlg1 = csr.SignatureAlgorithm;

            certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");


            // Add certificate extensions
            Asn1Set attributes = csr.GetCertificationRequestInfo().Attributes;

            if (attributes != null)
            {
                for (int i = 0; i != attributes.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(attributes[i]);

                    if (attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions1 = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier oid in extensions1.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions1.GetExtension(oid);

                            // !!! NOT working !!!
                            //certGen.AddExtension(oid, ext.IsCritical, ext.Value);

                            //OK
                            certGen.AddExtension(oid, ext.IsCritical, ext.Value, true);
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate issuedCert = null;
            try
            {
                issuedCert = certGen.Generate(issuerKeyPair.Private);
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generate certificate file." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Check if generated certificate file is valid, plase wait ..." + "\n";
                issuedCert.CheckValidity(DateTime.UtcNow);
                tbOutputMessageBox.Text += "Generate certificate file is valid." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Verify generated certificate file, plase wait ..." + "\n";
                issuedCert.Verify(issuerKeyPair.Public);
                tbOutputMessageBox.Text += "Generate certificate file verification is OK." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file verification is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            return(issuedCert);
        }
Exemplo n.º 19
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation("Certificate trigger function processed a request.");

            try
            {
                await ReadAppSettings(context, log);

                string requestBody          = await new StreamReader(req.Body).ReadToEndAsync();
                Certificate_Request request = JsonConvert.DeserializeObject <Certificate_Request>(requestBody);

                // Validate payload
                if (string.IsNullOrEmpty(request.RegistrationId) || string.IsNullOrEmpty(request.Csr))
                {
                    return(new BadRequestResult());
                }

                // Check if the device is authorized to request a certificate
                bool isAuthorized = CheckIfAuthorized(request.RegistrationId);

                if (isAuthorized)
                {
                    log.LogInformation($"{request.RegistrationId} is authorized.");

                    Pkcs10CertificationRequest decodedCsr = null;
                    RsaKeyParameters           publicKey  = null;
                    CertificationRequestInfo   info       = null;

                    // Get the signing certificate from a location
                    X509Certificate serverCertificate = ReadCertificate(cert, location, log);

                    if (serverCertificate == null)
                    {
                        throw new System.Exception("ReadCertificate() was unable to retrieve the signing certificate.");
                    }

                    // Get signing cert private key from a location.
                    AsymmetricKeyParameter serverPrivateKey = ReadPrivateKey(key, location, log);

                    if (serverPrivateKey == null)
                    {
                        throw new System.Exception("ReadPrivateKey() was unable to retrieve the private key.");
                    }

                    byte[] csr = Convert.FromBase64String(request.Csr);

                    // Decode DER
                    decodedCsr = new Pkcs10CertificationRequest(csr);
                    info       = decodedCsr.GetCertificationRequestInfo();
                    SubjectPublicKeyInfo publicKeyInfo = info.SubjectPublicKeyInfo;

                    RsaPublicKeyStructure publicKeyStructure = RsaPublicKeyStructure.GetInstance(publicKeyInfo.ParsePublicKey());

                    publicKey = new RsaKeyParameters(false, publicKeyStructure.Modulus, publicKeyStructure.PublicExponent);

                    bool certIsOK = decodedCsr.Verify(publicKey);

                    // Create the device certificate
                    X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

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

                    // Generate the device certificate
                    var deviceCert = generator.Generate(serverPrivateKey);

                    // Convert to DER
                    byte[] encoded = deviceCert.GetEncoded();

                    // Convert byte array to Base64 string
                    string encodedString = Convert.ToBase64String(encoded);

                    Certificate_Response responseMessage = new Certificate_Response
                    {
                        Certificate = encodedString
                    };

                    log.LogInformation($"Certificate issued for: {info.Subject}");

                    return(new OkObjectResult(responseMessage));
                }
                else
                {
                    log.LogError($"{request.RegistrationId} is NOT authorized.");

                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.Message);
            }

            return(new BadRequestResult());
        }