Beispiel #1
0
        /// <summary>
        /// Signs a cert request with the server CA certificate and returns
        /// a signed x509 certificate.
        /// </summary>
        /// <param name="serializedCsr">Is the serialized cert request (csr).</param>
        /// <returns>Signed x509 certificate.</returns>
        /// <exception cref="CertificateIOException">Thrown when the
        /// <see cref="serializedCsr"/> is either null or zero length.</exception>
        public X509Certificate SignCsr(byte[] serializedCsr)
        {
            if (serializedCsr == null || serializedCsr.Length == 0)
            {
                throw new Exception();
            }
            X509Certificate            issuer = GetCACert();
            Pkcs10CertificationRequest pkcsr  = DeserializeCsr(serializedCsr);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
            TimeSpan ts = DateTime.Now.Subtract(_serialNumStart);

            certGen.SetSerialNumber(BigInteger.ValueOf(ts.Ticks));
            certGen.SetIssuerDN(issuer.SubjectDN);
            certGen.SetNotBefore(DateTime.Today);
            certGen.SetNotAfter(DateTime.Today.AddDays(_certValidity));
            certGen.SetSubjectDN(pkcsr.GetCertificationRequestInfo().Subject);
            certGen.SetPublicKey(pkcsr.GetPublicKey());
            certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                 new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pkcsr.GetPublicKey())));
            certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(
                                     KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment));
            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory(HASH_ENCRYPTION_ALGORITHM, GetCAPrivKey(), new SecureRandom());

            return(certGen.Generate(signatureFactory));
        }
Beispiel #2
0
        /// <summary>
        /// Extract certificate signing request.
        /// </summary>
        /// <param name="csr">Certificate signing request.</param>
        /// <param name="publicKey">Asymmetric public key.</param>
        /// <param name="dn">Distinct name.</param>
        /// <param name="extensions">Extensions.</param>
        /// <exception cref="Exception"/>
        public static void ExtractCsr(Pkcs10CertificationRequest csr, out AsymmetricKeyParameter publicKey, out X509Name dn, out X509Extensions extensions)
        {
            if (csr is null)
            {
                throw new ArgumentNullException(nameof(csr));
            }
            publicKey = csr.GetPublicKey();
            CertificationRequestInfo csrInfo = csr.GetCertificationRequestInfo();

            dn = csrInfo.Subject;
            Dictionary <DerObjectIdentifier, X509Extension> attributes = new Dictionary <DerObjectIdentifier, X509Extension>();

            if (csrInfo.Attributes != null)
            {
                foreach (AttributePkcs attribute in csrInfo.Attributes)
                {
                    if (attribute.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        foreach (X509Extensions exts in attribute.AttrValues)
                        {
                            foreach (DerObjectIdentifier oid in exts.ExtensionOids)
                            {
                                X509Extension ext = exts.GetExtension(oid);
                                attributes.Add(oid, new X509Extension(ext.IsCritical, ext.Value));
                            }
                        }
                    }
                }
            }
            extensions = attributes.Count > 0 ? new X509Extensions(attributes) : null;
        }
 private byte[] MakeCertificateFromCSR(string CSR, AsymmetricCipherKeyPair rootKeyPair, X509Name rootSubject)
 {
     byte[] encoded;
     try
     {
         Pkcs10CertificationRequest pkcs10CertificationRequest = (Pkcs10CertificationRequest)(new PemReader(new StringReader(CSR))).ReadObject();
         AsymmetricKeyParameter     @private = rootKeyPair.Private;
         AsymmetricKeyParameter     @public  = rootKeyPair.Public;
         X509V3CertificateGenerator x509V3CertificateGenerator = new X509V3CertificateGenerator();
         x509V3CertificateGenerator.Reset();
         if (this.SerialNumber != -9223372036854775808L)
         {
             x509V3CertificateGenerator.SetSerialNumber(new BigInteger(this.SerialNumber.ToString()));
         }
         else
         {
             DateTime now = DateTime.Now;
             x509V3CertificateGenerator.SetSerialNumber(new BigInteger(128, new Random(now.Millisecond + Environment.TickCount)));
         }
         x509V3CertificateGenerator.SetIssuerDN(rootSubject);
         x509V3CertificateGenerator.SetNotBefore(this.ValidFrom.ToUniversalTime());
         x509V3CertificateGenerator.SetNotAfter(this.ValidTo.ToUniversalTime());
         x509V3CertificateGenerator.SetSubjectDN(pkcs10CertificationRequest.GetCertificationRequestInfo().Subject);
         x509V3CertificateGenerator.SetPublicKey(pkcs10CertificationRequest.GetPublicKey());
         x509V3CertificateGenerator.SetSignatureAlgorithm(string.Concat(this.SignatureAlgorithm.ToString(), "Encryption"));
         x509V3CertificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pkcs10CertificationRequest.GetPublicKey())));
         x509V3CertificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(@public)));
         int extensionType = 0;
         Asn1EncodableVector asn1EncodableVectors = new Asn1EncodableVector(new Asn1Encodable[0]);
         foreach (ExtensionInfo extension in this.Extensions.extensionInfo)
         {
             if (!extension.ExtendedKeyUsage)
             {
                 extensionType |= (int)extension.ExtensionType;
             }
             if (!extension.ExtendedKeyUsage)
             {
                 continue;
             }
             asn1EncodableVectors.Add(new Asn1Encodable[] { (Asn1Encodable)extension.ExtensionType });
         }
         if (extensionType != 0)
         {
             x509V3CertificateGenerator.AddExtension(X509Extensions.KeyUsage, this.Extensions.KeyUsageIsCritical, new KeyUsage(extensionType));
         }
         if (asn1EncodableVectors.Count > 0)
         {
             x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, this.Extensions.EnhancedKeyUsageIsCritical, ExtendedKeyUsage.GetInstance(new DerSequence(asn1EncodableVectors)));
         }
         X509Certificate x509Certificate = x509V3CertificateGenerator.Generate(@private, this.GetSecureRandom());
         x509Certificate.Verify(@public);
         encoded = x509Certificate.GetEncoded();
     }
     catch
     {
         throw;
     }
     return(encoded);
 }
Beispiel #4
0
        public override void Build(
            X509V3CertificateGenerator certGen,
            Pkcs10CertificationRequest request,
            X509Certificate caCert)
        {
            certGen.AddExtension(
                X509Extensions.AuthorityKeyIdentifier,
                false,
                new AuthorityKeyIdentifierStructure(caCert)
                );

            certGen.AddExtension(
                X509Extensions.SubjectKeyIdentifier,
                false,
                new SubjectKeyIdentifierStructure(request.GetPublicKey())
                );

            certGen.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(0xa0)
                );

            certGen.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                true,
                new ExtendedKeyUsage(new[]
            {
                new DerObjectIdentifier("1.3.6.1.4.1.311.20.2.2"),
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.2")
            })
                );

            ApplyCrlExtension(certGen, crlLink);

            var otherName = new Asn1EncodableVector
            {
                new DerObjectIdentifier("1.3.6.1.4.1.311.20.2.3"),
                new DerTaggedObject(true, GeneralName.OtherName, new DerUtf8String(upnName))
            };

            var upn = new DerTaggedObject(false, 0, new DerSequence(otherName));

            var generalNames = new Asn1EncodableVector {
                upn
            };

            certGen.AddExtension(
                X509Extensions.SubjectAlternativeName,
                false,
                new DerSequence(generalNames)
                );
        }
Beispiel #5
0
        private void generationTest(
            int keySize,
            string keyName,
            string sigName)
        {
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator(keyName);

//			kpg.initialize(keySize);
            kpg.Init(new KeyGenerationParameters(new SecureRandom(), keySize));

            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.EmailAddress, "*****@*****.**");

            IList order = new ArrayList();

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.EmailAddress);

            X509Name subject = new X509Name(order, attrs);

            Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest(
                sigName,
                subject,
                kp.Public,
                null,
                kp.Private);

            byte[] bytes = req1.GetEncoded();

            Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes);

            if (!req2.Verify())
            {
                Fail(sigName + ": Failed Verify check.");
            }

            if (!req2.GetPublicKey().Equals(req1.GetPublicKey()))
            {
                Fail(keyName + ": Failed public key check.");
            }
        }
Beispiel #6
0
        private static X509Certificate SignCertificateFromRequest(Pkcs10CertificationRequest request, ISignatureFactory signer)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            DateTime now = DateTime.Now;

            certGen.SetIssuerDN(request.GetCertificationRequestInfo().Subject);
            certGen.SetSubjectDN(request.GetCertificationRequestInfo().Subject);
            certGen.SetNotAfter(now.AddDays(7));
            certGen.SetNotBefore(now.AddMinutes(-10));
            certGen.SetSerialNumber(new Org.BouncyCastle.Math.BigInteger(80, new Random()));
            certGen.SetPublicKey(request.GetPublicKey());

            return(certGen.Generate(signer));
        }
        /// <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()));
        }
Beispiel #8
0
        public override void Build(X509V3CertificateGenerator certGen, Pkcs10CertificationRequest request, X509Certificate caCert)
        {
            const string demoBankCertExtension = "1.1.1.1.1.1.2";

            certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                 new AuthorityKeyIdentifierStructure(caCert));
            certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                 new SubjectKeyIdentifierStructure(request.GetPublicKey()));

            certGen.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                true,
                new ExtendedKeyUsage(new[]
            {
                new DerObjectIdentifier(demoBankCertExtension)
            })
                );
        }
Beispiel #9
0
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator pGen     = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters        genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25);

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.EmailAddress, "*****@*****.**");

            X509Name subject = new X509Name(new ArrayList(attrs.Keys), attrs);

            Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest(
                "SHA1withRSA",
                subject,
                pair.Public,
                null,
                pair.Private);

            byte[] bytes = req1.GetEncoded();

            Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes);

            if (!req2.Verify())
            {
                Fail("Failed verify check.");
            }

            if (!req2.GetPublicKey().Equals(req1.GetPublicKey()))
            {
                Fail("Failed public key check.");
            }
        }
Beispiel #10
0
        public X509Certificate IssueCertificate(
            Pkcs10CertificationRequest request,
            ExtensionBuilder extensionBuilder,
            string customDN = null
            )
        {
            var caCert = GetRootCert();
            var caKey  = GetRootKey();

            var startDate  = DateTime.Now;
            var expiryDate = DateTime.Now.AddYears(1);

            var serialNumber = BigIntegers.CreateRandomInRange(
                BigInteger.ValueOf(2).Pow(63),
                BigInteger.ValueOf(2).Pow(64),
                new SecureRandom()
                );

            var certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(serialNumber);
            certGen.SetIssuerDN(caCert.SubjectDN);
            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(expiryDate);
            certGen.SetPublicKey(request.GetPublicKey());

            if (!string.IsNullOrEmpty(customDN))
            {
                certGen.SetSubjectDN(new X509Name(customDN));
            }
            else
            {
                certGen.SetSubjectDN(request.GetCertificationRequestInfo().Subject);
            }

            extensionBuilder.Build(certGen, request, caCert);

            var x509Certificate = GenerateCertificate(caKey, certGen);

            return(x509Certificate);
        }
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator pGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25);

            pGen.Init(genParam);

            IAsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.EmailAddress, "*****@*****.**");

            X509Name subject = new X509Name(new ArrayList(attrs.Keys), attrs);

            Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest(
                "SHA1withRSA",
                subject,
                pair.Public,
                null,
                pair.Private);

            byte[] bytes = req1.GetEncoded();

            Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes);

            if (!req2.Verify())
            {
                Fail("Failed verify check.");
            }

            if (!req2.GetPublicKey().Equals(req1.GetPublicKey()))
            {
                Fail("Failed public key check.");
            }
        }
Beispiel #12
0
        // get key pair from two local files
        AsymmetricCipherKeyPair IPKIEncordeService.GetKeyPair(int keyType, int userID)
        {
            AsymmetricKeyParameter privateKey, publicKey;
            string path_project_bin  = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.IndexOf("bin\\")));
            var    privateKeyString  = "";
            var    certificateString = "";

            if (keyType == 0)
            {
                privateKeyString  = File.ReadAllText(path_project_bin + "/bin/keys/server/private.pem");
                certificateString = File.ReadAllText(path_project_bin + "/bin/keys/server/publicCert.pem");
            }
            else if (keyType == 1)
            {
                if (userID != 0)
                {
                    privateKeyString  = File.ReadAllText(path_project_bin + "/bin/keys/users/" + userID + "/private.pem");
                    certificateString = File.ReadAllText(path_project_bin + "/bin/keys/users/" + userID + "/publicCert.pem");
                }
            }

            using (var textReader = new StringReader(privateKeyString))
            {
                // Only a private key
                var pseudoKeyPair = (AsymmetricCipherKeyPair) new PemReader(textReader).ReadObject();
                privateKey = pseudoKeyPair.Private;
            }


            using (var textReader = new StringReader(certificateString))
            {
                // Only a private key
                Pkcs10CertificationRequest bcCertificate = (Pkcs10CertificationRequest) new PemReader(textReader).ReadObject();
                publicKey = bcCertificate.GetPublicKey();
            }

            return(new AsymmetricCipherKeyPair(publicKey, privateKey));
        }
Beispiel #13
0
        static bool Gen(string summoner, string region, string password, string file)
        {
            try
            {
                //Later in your Code

                //Requested Certificate Name
                X509Name name = new X509Name("CN=" + summoner + " - " + region + ", OU=Ghostblade Replays, O=Arsslensoft");

                //Key generation 2048bits
                RsaKeyPairGenerator rkpg = new RsaKeyPairGenerator();
                rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
                AsymmetricCipherKeyPair ackp   = rkpg.GenerateKeyPair();
                X509Certificate2        caCert = new X509Certificate2(GBReplay.Properties.Resources.GBSGN, "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6");
                //PKCS #10 Certificate Signing Request
                Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA256WITHRSA", name, ackp.Public, null, ackp.Private);


                AsymmetricKeyParameter publicKey = csr.GetPublicKey();

                // Build a Version1 (No Extensions) Certificate
                DateTime   startDate    = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
                DateTime   expiryDate   = startDate.AddYears(5);
                BigInteger serialNumber = new BigInteger(32, new Random());


                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

                X509Name dnName = new X509Name(caCert.Subject);

                certGen.SetSerialNumber(serialNumber);
                certGen.SetIssuerDN(dnName);
                certGen.SetNotBefore(startDate);
                certGen.SetNotAfter(expiryDate);
                certGen.SetSubjectDN(name);
                certGen.SetSignatureAlgorithm("SHA256WITHRSA");
                certGen.SetPublicKey(publicKey);

                UserNotice          unotice    = new UserNotice(null, "This certificate must be only used with Ghostblade replays files. This certificate is a property of Arsslensoft any usage of its content without prior request is prohibited.");
                PolicyQualifierInfo pqiunotice = new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, unotice);
                PolicyInformation   p          = new PolicyInformation(new DerObjectIdentifier("1.3.6.1.4.1.44215.1.3"), new DerSequence(new PolicyQualifierInfo[1] {
                    pqiunotice
                }));
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(DotNetUtilities.FromX509Certificate(caCert).GetPublicKey()));
                certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey));
                certGen.AddExtension(X509Extensions.KeyUsage, false, new  KeyUsage(KeyUsage.DigitalSignature));
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new  ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPCodeSigning }));

                certGen.AddExtension(X509Extensions.CertificatePolicies, false, new DerSequence(p));



                Pkcs12Store pfx   = new Pkcs12Store(new MemoryStream(GBReplay.Properties.Resources.GBSGN), "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6".ToCharArray());
                string      alias = null;
                foreach (string al in pfx.Aliases)
                {
                    if (pfx.IsKeyEntry(al) && pfx.GetKey(al).Key.IsPrivate)
                    {
                        alias = al;
                        break;
                    }
                }

                //get our Private Key to Sign with

                //   AsymmetricCipherKeyPair caPair = DotNetUtilities.GetKeyPair(caCert.PrivateKey);
                AsymmetricKeyParameter caPair = pfx.GetKey(alias).Key;

                Al.Security.X509.X509Certificate cert = certGen.Generate(caPair);

                Pkcs12Store pk = new Pkcs12StoreBuilder().Build();
                // Add a Certificate entry
                X509CertificateEntry certEntry = new X509CertificateEntry(cert);
                pk.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

                AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(ackp.Private);
                pk.SetKeyEntry(cert.SubjectDN.ToString(), keyEntry, new X509CertificateEntry[] { certEntry }); // Note that we only have 1 cert in the 'chain'

                using (var filestream = new FileStream(file, FileMode.Create, FileAccess.ReadWrite))
                    pk.Save(filestream, password.ToCharArray(), new SecureRandom());

                X509Certificate2 cer = new X509Certificate2(File.ReadAllBytes(file), password);
                cer.Verify();
            }
            catch
            {
                return(false);
            }
            return(true);
        }
        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);
        }
        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");
        }
Beispiel #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);
        }
Beispiel #17
0
        public PkiCertificateSigningRequest(PkiEncodingFormat format, byte[] encoded,
                                            PkiHashAlgorithm hashAlgorithm)
        {
            Pkcs10CertificationRequest pkcs10;

            switch (format)
            {
            case PkiEncodingFormat.Pem:
                var encodedString = Encoding.UTF8.GetString(encoded);
                using (var sr = new StringReader(encodedString))
                {
                    var pemReader = new PemReader(sr);
                    pkcs10 = pemReader.ReadObject() as Pkcs10CertificationRequest;
                    if (pkcs10 == null)
                    {
                        throw new Exception("invalid PEM object is not PKCS#10 archive");
                    }
                }
                break;

            case PkiEncodingFormat.Der:
                pkcs10 = new Pkcs10CertificationRequest(encoded);
                break;

            default:
                throw new NotSupportedException();
            }

            var info            = pkcs10.GetCertificationRequestInfo();
            var nativePublicKey = pkcs10.GetPublicKey();
            var rsaKey          = nativePublicKey as RsaKeyParameters;
            var ecdsaKey        = nativePublicKey as ECPublicKeyParameters;

            if (rsaKey != null)
            {
                PublicKey = new PkiKey(nativePublicKey, PkiAsymmetricAlgorithm.Rsa);
            }
            else if (ecdsaKey != null)
            {
                PublicKey = new PkiKey(nativePublicKey, PkiAsymmetricAlgorithm.Ecdsa);
            }
            else
            {
                throw new NotSupportedException("unsupported asymmetric algorithm key");
            }
            SubjectName   = info.Subject.ToString();
            HashAlgorithm = hashAlgorithm;


            // // // Based on:
            // // //    http://forum.rebex.net/4284/pkcs10-certificate-request-example-provided-castle-working

            // // var extGen = new X509ExtensionsGenerator();
            // // foreach (var ext in CertificateExtensions)
            // // {
            // //     extGen.AddExtension(ext.Identifier, ext.IsCritical, ext.Value);
            // // }
            // // var attr = new AttributeX509(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
            // //         new DerSet(extGen.Generate()));


            // Based on:
            //    http://unitstep.net/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/
            //    https://stackoverflow.com/q/24448909/5428506
            foreach (var attr in info.Attributes.ToArray())
            {
                if (attr is DerSequence derSeq && derSeq.Count == 2)
                {
                    var attrX509 = AttributeX509.GetInstance(attr);
                    if (object.Equals(attrX509.AttrType, PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        // The `Extension Request` attribute is present.
                        // The X509Extensions are contained as a value of the ASN.1 Set.
                        // Assume that it is the first value of the set.
                        if (attrX509.AttrValues.Count >= 1)
                        {
                            var csrExts = X509Extensions.GetInstance(attrX509.AttrValues[0]);
                            foreach (var extOid in csrExts.GetExtensionOids())
                            {
                                if (object.Equals(extOid, X509Extensions.SubjectAlternativeName))
                                {
                                    var ext    = csrExts.GetExtension(extOid);
                                    var extVal = ext.Value;
                                    var der    = extVal.GetDerEncoded();
                                    // The ext value, which is an ASN.1 Octet String, **MIGHT** be tagged with
                                    // a leading indicator that it's an Octet String and its length, so we want
                                    // to remove it if that's the case to extract the GeneralNames collection
                                    if (der.Length > 2 && der[0] == 4 && der[1] == der.Length - 2)
                                    {
                                        der = der.Skip(2).ToArray();
                                    }
                                    var asn1obj = Asn1Object.FromByteArray(der);
                                    var gnames  = GeneralNames.GetInstance(asn1obj);
                                    CertificateExtensions.Add(new PkiCertificateExtension
                                    {
                                        Identifier = extOid,
                                        IsCritical = ext.IsCritical,
                                        Value      = gnames,
                                    });
                                }
                            }

                            // No need to search any more.
                            break;
                        }
                    }
                }
            }
        }
Beispiel #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);
        }