示例#1
0
        public static void ValidateCertificate(X509Certificate cert)
        {
            //IL_000e: Unknown result type (might be due to invalid IL or missing references)
            if (cert.Version != 3)
            {
                throw new ArgumentException("Certificate must have an ExtendedKeyUsage extension.");
            }
            Asn1OctetString extensionValue = cert.GetExtensionValue(X509Extensions.ExtendedKeyUsage);

            if (extensionValue == null)
            {
                throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension.");
            }
            if (!cert.GetCriticalExtensionOids().Contains(X509Extensions.ExtendedKeyUsage.Id))
            {
                throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical.");
            }
            try
            {
                ExtendedKeyUsage instance = ExtendedKeyUsage.GetInstance(Asn1Object.FromByteArray(extensionValue.GetOctets()));
                if (!instance.HasKeyPurposeId(KeyPurposeID.IdKPTimeStamping) || instance.Count != 1)
                {
                    throw new TspValidationException("ExtendedKeyUsage not solely time stamping.");
                }
            }
            catch (IOException)
            {
                throw new TspValidationException("cannot process ExtendedKeyUsage extension");
            }
        }
示例#2
0
        /// <summary>
        /// The Alias Certificate is a certificate over the Alias Public key (+ the RIoT attestation extension) signed by the
        /// DeviceID key.
        /// </summary>
        /// <param name="deviceID">The cert siging key</param>
        /// <param name="aliasKey">The key being certified</param>
        /// <param name="fwid">The (simulated) hash of the upper-level firmware</param>
        /// <param name="signingSeed">Seed for the signing BRBG</param>
        /// <returns>The alias certificate</returns>
        private static X509Certificate CreateAliasCert(AsymmetricCipherKeyPair deviceID, AsymmetricCipherKeyPair aliasKey, byte[] fwid, byte[] signingSeed)
        {
            var random = GetDrbg(signingSeed, SeedUsage.Signing);

            // set standard fields in TBS structure
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(GetSerialNumber(random));
            certGen.SetIssuerDN(rDeviceCertSubject);
            certGen.SetSubjectDN(rAliasCertSubject);
            certGen.SetNotBefore(startTime);
            certGen.SetNotAfter(endTime);
            certGen.SetPublicKey(aliasKey.Public);

            // add extensions
            certGen.AddExtension(X509Extensions.ExtendedKeyUsage, true, ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPClientAuth)));
            certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature));
            var riotExtension = CreateRIoTExtension(fwid, deviceID.Public);

            certGen.AddExtension(new DerObjectIdentifier(rExtensionOID), false, riotExtension);
            certGen.AddExtension(
                X509Extensions.AuthorityKeyIdentifier,
                false,
                new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(deviceID.Public)));
            certGen.AddExtension(
                X509Extensions.SubjectKeyIdentifier,
                false,
                new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aliasKey.Public)));

            // sign and return
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(rSigSch, deviceID.Private, random);
            var certificate = certGen.Generate(signatureFactory);

            return(certificate);
        }
示例#3
0
        public static ExtendedKeyUsage retrieveExtendedKeyUsageOIDs(X509Certificate x509Certificate)
        {
            ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage();

            X509Extension x509Extension = x509Certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(new DerObjectIdentifier(OIDS.OID_EXTENDED_KEY_USAGE_EXTENSION));

            if (x509Extension != null)
            {
                Org.BouncyCastle.Asn1.X509.ExtendedKeyUsage extendedKeyUsageExtension = Org.BouncyCastle.Asn1.X509.ExtendedKeyUsage.GetInstance(x509Extension);
                extendedKeyUsage.HasExtendedKeyUsageExtension = true;
                extendedKeyUsage.IsCritical = x509Extension.IsCritical;
                IList allUsages = extendedKeyUsageExtension.GetAllUsages();
                extendedKeyUsage.Count = allUsages.Count;

                List <byte[]> purposeOidList = new List <byte[]>(allUsages.Count);
                foreach (DerObjectIdentifier derObjectIdentifier in allUsages)
                {
                    purposeOidList.Add(StringUtil.StringToByteArray(derObjectIdentifier.Id));
                }

                extendedKeyUsage.Oids = purposeOidList.ToArray();
            }
            else
            {
                extendedKeyUsage.HasExtendedKeyUsageExtension = false;
            }

            return(extendedKeyUsage);
        }
示例#4
0
        /// <inheritdoc />
        public override void InjectReferenceValue(X509Certificate2 value)
        {
            Certificate = value;

            Asn1Object exValue = GetExtensionValue(value);

            if (exValue == null)
            {
                if (IsRequired())
                {
                    throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present.");
                }

                PolicyValue = new PolicyValue <IList <string> >(new List <string>());
                return;
            }

            ExtendedKeyUsage usages      = ExtendedKeyUsage.GetInstance(exValue);
            IList            purposeList = usages.GetAllUsages();

            var usageList = new List <string>();

            foreach (DerObjectIdentifier purpose in purposeList)
            {
                usageList.Add(purpose.Id);
            }

            PolicyValue = new PolicyValue <IList <string> >(usageList);
        }
示例#5
0
        /**
         * Validate the passed in certificate as being of the correct type to be used
         * for time stamping. To be valid it must have an ExtendedKeyUsage extension
         * which has a key purpose identifier of id-kp-timeStamping.
         *
         * @param cert the certificate of interest.
         * @throws TspValidationException if the certicate fails on one of the check points.
         */
        public static void ValidateCertificate(
            X509Certificate cert)
        {
            if (cert.Version != 3)
            {
                throw new ArgumentException("Certificate must have an ExtendedKeyUsage extension.");
            }

            Asn1OctetString ext = cert.GetExtensionValue(X509Extensions.ExtendedKeyUsage);

            if (ext == null)
            {
                throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension.");
            }

            if (!cert.GetCriticalExtensionOids().Contains(X509Extensions.ExtendedKeyUsage.Id))
            {
                throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical.");
            }

            try
            {
                ExtendedKeyUsage extKey = ExtendedKeyUsage.GetInstance(
                    Asn1Object.FromByteArray(ext.GetOctets()));

                if (!extKey.HasKeyPurposeId(KeyPurposeID.IdKPTimeStamping) || extKey.Count != 1)
                {
                    throw new TspValidationException("ExtendedKeyUsage not solely time stamping.");
                }
            }
            catch (IOException)
            {
                throw new TspValidationException("cannot process ExtendedKeyUsage extension");
            }
        }
示例#6
0
        private static X509Certificate GenerateCertificate(X509Name subject, X509Name issuer,
                                                           int iValidity, AsymmetricKeyParameter publicKey,
                                                           AsymmetricKeyParameter privateKey, String signatureType,
                                                           int keyusages, ExtendedKeyUsage extendedKeyUsages, bool isCA,
                                                           int pathLenConstraint)
        {
            // Get an X509 Version 1 Certificate generator
            var certGen = new X509V3CertificateGenerator();

            // Load the generator with generation parameters

            // Set the issuer distinguished name
            certGen.SetIssuerDN(issuer);

            // Valid before and after dates now to iValidity days in the future
            certGen.SetNotBefore(DateTime.Now);
            certGen.SetNotAfter(DateTime.Now.AddDays(iValidity));

            // Set the subject distinguished name (same as issuer for our purposes)
            certGen.SetSubjectDN(subject);

            // Set the public key
            certGen.SetPublicKey(publicKey);

            // Set the algorithm
            certGen.SetSignatureAlgorithm(signatureType);

            // Set the serial number
            //read the serial number
            String serial   = Repository.Instance.ReadSerialNumber();
            var    biSerial = new BigInteger(serial, Repository.SerialNumberRadix);

            certGen.SetSerialNumber(biSerial);

            certGen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(keyusages));
            if (extendedKeyUsages != null)
            {
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, extendedKeyUsages);
            }
            if (isCA)
            {
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(pathLenConstraint));
            }

            try
            {
                // Generate an X.509 certificate, based on the current issuer and subject
                return(certGen.Generate(privateKey));
            }
            // Something went wrong
            //catch (GeneralSecurityException ex)
            //{
            //    throw new CryptoException(ex.Message,ex);
            //}
            finally
            {
                Repository.Instance.IncrementSerial();
            }
        }
示例#7
0
 /// <summary>
 /// Generates a user certificate
 /// </summary>
 /// <param name="subject">X509Name subject name </param>
 /// <param name="issuer">X509Name issuer name</param>
 /// <param name="iValidity">validity in days</param>
 /// <param name="publicKey">publickey</param>
 /// <param name="privateKey">private key of the issuer</param>
 /// <param name="signatureType">signature type</param>
 /// <param name="keyusages">keyusages, <see>Org.BouncyCastle.Asn1.X509.KeyUsage</see></param>
 /// <param name="extendedKeyUsages">extendedKeyUsages <see>Org.BouncyCastle.Asn1.X509.KeyPurposeID</see></param>
 /// <returns>brand new generated X509Certificate</returns>
 public static X509Certificate GenerateUserCertificate(X509Name subject, X509Name issuer,
                                                       int iValidity, AsymmetricKeyParameter publicKey,
                                                       AsymmetricKeyParameter privateKey, String signatureType,
                                                       int keyusages, ExtendedKeyUsage extendedKeyUsages)
 {
     return(GenerateCertificate(subject, issuer, iValidity, publicKey, privateKey, signatureType, keyusages,
                                extendedKeyUsages, false, 0));
 }
示例#8
0
        public static ICertificateBuilder WithExtendedKeyUsage(this ICertificateBuilder builder)
        {
            var extendedKeyUsage = new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth);

            builder.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, extendedKeyUsage);

            return(builder);
        }
示例#9
0
        public static TimestampService Create(
            CertificateAuthority certificateAuthority,
            TimestampServiceOptions serviceOptions = null)
        {
            if (certificateAuthority == null)
            {
                throw new ArgumentNullException(nameof(certificateAuthority));
            }

            serviceOptions = serviceOptions ?? new TimestampServiceOptions();

            var keyPair     = CertificateUtilities.CreateKeyPair();
            var id          = Guid.NewGuid().ToString();
            var subjectName = new X509Name($"C=US,ST=WA,L=Redmond,O=NuGet,CN=NuGet Test Timestamp Service ({id})");

            Action <X509V3CertificateGenerator> customizeCertificate = generator =>
            {
                generator.AddExtension(
                    X509Extensions.AuthorityInfoAccess,
                    critical: false,
                    extensionValue: new DerSequence(
                        new AccessDescription(AccessDescription.IdADOcsp,
                                              new GeneralName(GeneralName.UniformResourceIdentifier, certificateAuthority.OcspResponderUri.OriginalString)),
                        new AccessDescription(AccessDescription.IdADCAIssuers,
                                              new GeneralName(GeneralName.UniformResourceIdentifier, certificateAuthority.CertificateUri.OriginalString))));
                generator.AddExtension(
                    X509Extensions.AuthorityKeyIdentifier,
                    critical: false,
                    extensionValue: new AuthorityKeyIdentifierStructure(certificateAuthority.Certificate));
                generator.AddExtension(
                    X509Extensions.SubjectKeyIdentifier,
                    critical: false,
                    extensionValue: new SubjectKeyIdentifierStructure(keyPair.Public));
                generator.AddExtension(
                    X509Extensions.BasicConstraints,
                    critical: true,
                    extensionValue: new BasicConstraints(cA: false));
                generator.AddExtension(
                    X509Extensions.KeyUsage,
                    critical: true,
                    extensionValue: new KeyUsage(KeyUsage.DigitalSignature));
                generator.AddExtension(
                    X509Extensions.ExtendedKeyUsage,
                    critical: true,
                    extensionValue: ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPTimeStamping)));
            };

            var issueOptions = new IssueCertificateOptions()
            {
                KeyPair              = keyPair,
                SubjectName          = subjectName,
                CustomizeCertificate = customizeCertificate
            };
            var certificate = certificateAuthority.IssueCertificate(issueOptions);
            var uri         = certificateAuthority.GenerateRandomUri();

            return(new TimestampService(certificateAuthority, certificate, keyPair, uri, serviceOptions));
        }
        public static ExtendedKeyUsage convertExtendedKeyUsage(NativeExtendedKeyUsage nativeExtendedKeyUsage)
        {
            ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage();

            extendedKeyUsage.HasExtendedKeyUsageExtension = nativeExtendedKeyUsage.HasExtendedKeyUsageExtension;
            extendedKeyUsage.IsCritical = nativeExtendedKeyUsage.IsCritical;
            extendedKeyUsage.Oids       = convertStringMapToArray(nativeExtendedKeyUsage.Oids);
            return(extendedKeyUsage);
        }
示例#11
0
 /// <summary>
 /// Generates a CA certificate.
 /// </summary>
 /// <param name="subject">X509Name subject name </param>
 /// <param name="iValidity">validity in days</param>
 /// <param name="publicKey">publickey</param>
 /// <param name="privateKey">private key of the issuer</param>
 /// <param name="signatureType">signature type</param>
 /// <param name="keyusages">keyusages, <see>Org.BouncyCastle.Asn1.X509.KeyUsage</see></param>
 /// <param name="extendedKeyUsages">extendedKeyUsages <see>Org.BouncyCastle.Asn1.X509.KeyPurposeID</see></param>
 /// <param name="pathLenConstraint"> </param>
 /// <returns>brand new generated X509Certificate</returns>
 public static X509Certificate GenerateCACertificate(X509Name subject,
                                                     int iValidity, AsymmetricKeyParameter publicKey,
                                                     AsymmetricKeyParameter privateKey, String signatureType,
                                                     int keyusages, ExtendedKeyUsage extendedKeyUsages,
                                                     int pathLenConstraint)
 {
     return(GenerateCertificate(subject, subject, iValidity, publicKey, privateKey, signatureType, keyusages,
                                extendedKeyUsages, true, pathLenConstraint));
 }
示例#12
0
        private (bool, ExtendedKeyUsage) GetExtendedUsage()
        {
            var purposes = cbCsrExtendedUsage.CheckedItems.Cast <string>()
                           .Select(item => extKeyUsageDictionary.Where(x => x.Value == item).Select(x => x.Key).Single())
                           .ToArray();
            bool             extKeyUsageCritical = cbCsrExtendedUsageCritical.Checked;
            ExtendedKeyUsage extendedKeyUsageExt = purposes.Length != 0 || extKeyUsageCritical ? new ExtendedKeyUsage(purposes) : null;

            return(extKeyUsageCritical, extendedKeyUsageExt);
        }
示例#13
0
        /// <summary>
        /// Create ExtendedKeyUsage from an X509Extension
        /// </summary>
        /// <param name="Extension">X509 extension</param>
        /// <remarks>
        /// Sub classses must provide an implementation to decode their values
        /// </remarks>
        public extendedKeyUsage(X509Extension Extension) : base(Extension)
        {
            base.oid         = X509Extensions.ExtendedKeyUsage;
            base.name        = "ExtendedKeyUsage";
            base.displayName = "Extended Key Usage";

            ExtendedKeyUsage eku = ExtendedKeyUsage.GetInstance(Extension);

            // Lookup each OID in the extension and add to usage List by name
            foreach (var e in eku.GetAllUsages())
            {
                usage.Add(ekuNames[e.ToString()]);
            }
        }
示例#14
0
        private bool ValidateAlternateSigner(X509Certificate certificate, X509Certificate issuer)
        {
            byte[]           bytes            = certificate.GetExtensionValue(new DerObjectIdentifier(X509Extensions.ExtendedKeyUsage.Id)).GetOctets();
            Asn1InputStream  aIn              = new Asn1InputStream(bytes);
            var              As1              = aIn.ReadObject();
            ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.GetInstance(As1);
            var              extendedKey      = extendedKeyUsage.GetAllUsages().Cast <DerObjectIdentifier>().ToList();

            if (extendedKey.Any(x => x.Id == "1.3.6.1.5.5.7.3.9"))
            {
                certificate.Verify(issuer.GetPublicKey());
                return(true);
            }
            return(false);
        }
        private static X509Certificate2 GenerateAndSignCertificate(
            X509Name subjectName,
            X509Name issuerName,
            AsymmetricKeyParameter privateSigningKey)
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);
            var certGenerator   = new X509V3CertificateGenerator();

            var keyGenerationParameters = new KeyGenerationParameters(random, 256);
            var keyPairGenerator        = new ECKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair certKeyPair = keyPairGenerator.GenerateKeyPair();

            certGenerator.SetPublicKey(certKeyPair.Public);

            var serialNumber = new BigInteger(64, random);

            certGenerator.SetSerialNumber(serialNumber);

            certGenerator.SetSubjectDN(subjectName);
            certGenerator.SetIssuerDN(issuerName);

            DateTime notBefore = DateTime.UtcNow - TimeSpan.FromDays(3);
            DateTime notAfter  = DateTime.UtcNow + TimeSpan.FromDays(3);

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

            certGenerator.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                true,
                ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPClientAuth)));

            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory("SHA256WITHECDSA", privateSigningKey, random);

            var certificate = certGenerator.Generate(signatureFactory);

            return(new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate)));
        }
示例#16
0
        public static X509Certificate MakeCertificate(AsymmetricCipherKeyPair _subKP,
                                                      string _subDN, AsymmetricCipherKeyPair _issKP, string _issDN, bool _ca)
        {
            AsymmetricKeyParameter _subPub  = _subKP.Public;
            AsymmetricKeyParameter _issPriv = _issKP.Private;
            AsymmetricKeyParameter _issPub  = _issKP.Public;

            X509V3CertificateGenerator _v3CertGen = new X509V3CertificateGenerator();

            _v3CertGen.Reset();
            _v3CertGen.SetSerialNumber(allocateSerialNumber());
            _v3CertGen.SetIssuerDN(new X509Name(_issDN));
            _v3CertGen.SetNotBefore(DateTime.UtcNow);
            _v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100));
            _v3CertGen.SetSubjectDN(new X509Name(_subDN));
            _v3CertGen.SetPublicKey(_subPub);
            _v3CertGen.SetSignatureAlgorithm("MD5WithRSAEncryption");

            _v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                    createSubjectKeyId(_subPub));

            _v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                    createAuthorityKeyId(_issPub));

            if (_ca)
            {
                _v3CertGen.AddExtension(X509Extensions.BasicConstraints, false,
                                        new BasicConstraints(_ca));
            }
            else
            {
                _v3CertGen.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                        ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPTimeStamping)));
            }

            X509Certificate _cert = _v3CertGen.Generate(_issPriv);

            _cert.CheckValidity(DateTime.UtcNow);
            _cert.Verify(_issPub);

            return(_cert);
        }
示例#17
0
 private void OkBtn_Click(object sender, EventArgs e)
 {
     try
     {
         SystemTitle = GXDLMSTranslator.HexToBytes(SystemTitleTb.Text);
         if (SystemTitle.Length != 8)
         {
             throw new ArgumentOutOfRangeException("Invalid system title.");
         }
         if (DigitalSignatureCb.Checked)
         {
             CertificateType = CertificateType.DigitalSignature;
         }
         else if (KeyAgreementCb.Checked)
         {
             CertificateType = CertificateType.KeyAgreement;
         }
         else
         {
             if (ServerTlsCb.Checked)
             {
                 ExtendedKeyUsage = ExtendedKeyUsage.ServerAuth;
             }
             else
             {
                 ExtendedKeyUsage = ExtendedKeyUsage.ClientAuth;
             }
             CertificateType = CertificateType.TLS;
         }
     }
     catch (Exception ex)
     {
         DialogResult = DialogResult.None;
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
示例#18
0
        static void Main(string[] args)
        {
            foreach (string s in args)
            {
                if (s.StartsWith("-out:"))
                {
                    outputfile = s.Replace("-out:", "");
                }
                if (s.StartsWith("-in:"))
                {
                    certfile = s.Replace("-in:", "");
                }
            }
            if (outputfile != "stdout")
            {
                str = new StreamWriter(outputfile, false);
            }
            System.Security.Cryptography.X509Certificates.X509Certificate2 cer = new System.Security.Cryptography.X509Certificates.X509Certificate2(File.ReadAllBytes(certfile));
            Al.Security.X509.X509Certificate CERT = Al.Security.Security.DotNetUtilities.FromX509Certificate(cer);
            Print("Certificate");
            Print("     Data");
            Print("         Version : " + cer.Version.ToString());
            Print("         Valid : " + cer.Verify().ToString());
            Print("         Serial Number:");
            Print("             " + cer.SerialNumber);
            Print("         Signature Algorithm : ");
            Print("             " + cer.SignatureAlgorithm.FriendlyName);
            Print("         Issuer   : " + cer.Issuer);
            Print("         Validity :   ");
            Print("             Not Before : " + GetRFC822Date(cer.NotBefore));
            Print("             Not After  : " + GetRFC822Date(cer.NotAfter));
            Print("         Subject  : " + cer.Subject);
            Print("         Subject Public Key Info:");
            Print("             Public Key Exchange Algorithm: " + cer.PublicKey.Key.KeyExchangeAlgorithm);
            Print("             Public Key: " + cer.PublicKey.Key.KeySize.ToString() + " bit");
            Print("             Modulus:");
            Print(cer.GetPublicKey(), "              ");
            if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.RsaKeyParameters)
            {
                RsaKeyParameters rsa = (RsaKeyParameters)CERT.GetPublicKey();
                Print("             Exponent:" + rsa.Exponent);
            }
            else if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.DsaKeyParameters)
            {
                DsaKeyParameters dsa = (DsaKeyParameters)CERT.GetPublicKey();
                Print("             DSA Parameters:");
                Print("                 G:");
                Print("                     " + dsa.Parameters.G.ToString());
                Print("                 P:");
                Print("                     " + dsa.Parameters.P.ToString());
                Print("                 Q:");
                Print("                     " + dsa.Parameters.Q.ToString());
            }
            // Extensions
            Print("         X509 Extensions");
            string extab    = "            ";
            bool   critical = true;

            foreach (string oid in CERT.GetCriticalExtensionOids())
            {
                Print(" ");

                X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid));

                if (oid == X509Extensions.BasicConstraints.Id)
                {
                    BasicConstraints bc = BasicConstraints.GetInstance(ext);
                    Print(extab + "Basic Constraints Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     CA:" + bc.IsCA().ToString());
                    if (bc.PathLenConstraint != null)
                    {
                        Print(extab + "     Path Length:" + bc.PathLenConstraint.ToString());
                    }
                    else
                    {
                        Print(extab + "     Path Length:Null");
                    }
                }
                else if (oid == X509Extensions.KeyUsage.Id)
                {
                    KeyUsage keyu = KeyUsage.GetInstance(ext);
                    Print(extab + "Key Usage Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Usages:" + keyu.ToString());
                }
                else if (oid == X509Extensions.ExtendedKeyUsage.Id)
                {
                    ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext);



                    Print(extab + "Extended Key Usage Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Extended Key Usages:");
                    foreach (DerObjectIdentifier id in keyu.GetAllUsages())
                    {
                        Print(extab + "         " + id.Id);
                    }
                }
                else if (oid == X509Extensions.SubjectKeyIdentifier.Id)
                {
                    SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext);
                    Print(extab + "Subject Key Identifier Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Identifier:");
                    Print(keyu.GetKeyIdentifier(), extab + "         ");
                }
                else if (oid == X509Extensions.AuthorityKeyIdentifier.Id)
                {
                    AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext);
                    Print(extab + "Authority Key Identifier Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Identifier:");
                    Print(keyu.GetKeyIdentifier(), extab + "         ");
                }
                else if (oid == X509Extensions.SubjectAlternativeName.Id)
                {
                    Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                    GeneralNames keyu = GeneralNames.GetInstance(asn1Object);

                    Print(extab + "Subject Alternative Name Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     General Names:");

                    foreach (GeneralName gen in keyu.GetNames())
                    {
                        string tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }

                        Print(extab + "         " + tagname + " " + gen.Name);
                    }
                }
                else if (oid == X509Extensions.IssuerAlternativeName.Id)
                {
                    Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                    GeneralNames keyu = GeneralNames.GetInstance(asn1Object);

                    Print(extab + "Issuer Alternative Name Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     General Names:");

                    foreach (GeneralName gen in keyu.GetNames())
                    {
                        string tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }

                        Print(extab + "         " + tagname + " " + gen.Name);
                    }
                }
                else if (oid == X509Extensions.AuthorityInfoAccess.Id)
                {
                    AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext);
                    Print(extab + "Authority Information Access Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Access Descriptions:");
                    foreach (AccessDescription acc in keyu.GetAccessDescriptions())
                    {
                        Print(extab + "         Method:" + acc.AccessMethod.Id);
                        GeneralName gen     = acc.AccessLocation;
                        string      tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }
                        Print(extab + "         Access Location:" + tagname + "=" + gen.Name);
                    }
                }
                else if (oid == X509Extensions.SubjectInfoAccess.Id)
                {
                    AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext);
                    Print(extab + "Subject Information Access Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Access Descriptions:");
                    foreach (AccessDescription acc in keyu.GetAccessDescriptions())
                    {
                        Print(extab + "         Method:" + acc.AccessMethod.Id);
                        GeneralName gen     = acc.AccessLocation;
                        string      tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }
                        Print(extab + "         Access Location:" + tagname + "=" + gen.Name);
                    }
                }
                else if (oid == X509Extensions.CrlDistributionPoints.Id)
                {
                    Asn1Object   asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);
                    CrlDistPoint keyu       = CrlDistPoint.GetInstance(asn1Object);


                    Print(extab + "Crl Distribution Points Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Distribution Points:");
                    foreach (DistributionPoint acc in keyu.GetDistributionPoints())
                    {
                        if (acc.Reasons != null)
                        {
                            Print(extab + "         Reasons:" + acc.Reasons.GetString());
                        }
                        else
                        {
                            Print(extab + "         Reasons:Null");
                        }

                        if (acc.CrlIssuer != null)
                        {
                            Print(extab + "         Crl Issuer:");
                            foreach (GeneralName gen in acc.CrlIssuer.GetNames())
                            {
                                string tagname = "Dns Name:";
                                if (gen.TagNo == GeneralName.EdiPartyName)
                                {
                                    tagname = "Edi Party Name:";
                                }
                                else if (gen.TagNo == GeneralName.IPAddress)
                                {
                                    tagname = "IP Address:";
                                }
                                else if (gen.TagNo == GeneralName.OtherName)
                                {
                                    tagname = "Other Name:";
                                }
                                else if (gen.TagNo == GeneralName.RegisteredID)
                                {
                                    tagname = "Registered ID:";
                                }
                                else if (gen.TagNo == GeneralName.Rfc822Name)
                                {
                                    tagname = "Rfc822 Name:";
                                }
                                else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                                {
                                    tagname = "URI:";
                                }
                                else if (gen.TagNo == GeneralName.X400Address)
                                {
                                    tagname = "X400 Address:";
                                }
                                else if (gen.TagNo == GeneralName.DirectoryName)
                                {
                                    tagname = "Directory Name:";
                                }
                                Print(extab + "            " + tagname + ": " + gen.Name);
                            }
                        }
                        else
                        {
                            Print(extab + "         Crl Issuer:Null");
                        }
                        Print(extab + "         Distribution Point Name:");
                        if (acc.DistributionPointName.PointType == DistributionPointName.FullName)
                        {
                            GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name);
                            foreach (GeneralName gen in sgen.GetNames())
                            {
                                string tagname = "Dns Name:";
                                if (gen.TagNo == GeneralName.EdiPartyName)
                                {
                                    tagname = "Edi Party Name:";
                                }
                                else if (gen.TagNo == GeneralName.IPAddress)
                                {
                                    tagname = "IP Address:";
                                }
                                else if (gen.TagNo == GeneralName.OtherName)
                                {
                                    tagname = "Other Name:";
                                }
                                else if (gen.TagNo == GeneralName.RegisteredID)
                                {
                                    tagname = "Registered ID:";
                                }
                                else if (gen.TagNo == GeneralName.Rfc822Name)
                                {
                                    tagname = "Rfc822 Name:";
                                }
                                else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                                {
                                    tagname = "URI:";
                                }
                                else if (gen.TagNo == GeneralName.X400Address)
                                {
                                    tagname = "X400 Address:";
                                }
                                else if (gen.TagNo == GeneralName.DirectoryName)
                                {
                                    tagname = "Directory Name:";
                                }
                                Print(extab + "                " + tagname + " " + gen.Name);
                            }
                        }
                        else
                        {
                            Print(extab + "                Not Supported by OCT");
                        }
                    }
                }
            }
            critical = false;
            foreach (string oid in CERT.GetNonCriticalExtensionOids())
            {
                Print(" ");

                X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid));

                if (oid == X509Extensions.BasicConstraints.Id)
                {
                    BasicConstraints bc = BasicConstraints.GetInstance(ext);
                    Print(extab + "Basic Constraints Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     CA:" + bc.IsCA().ToString());
                    if (bc.PathLenConstraint != null)
                    {
                        Print(extab + "     Path Length:" + bc.PathLenConstraint.ToString());
                    }
                    else
                    {
                        Print(extab + "     Path Length:Null");
                    }
                }
                else if (oid == X509Extensions.KeyUsage.Id)
                {
                    KeyUsage keyu = KeyUsage.GetInstance(ext);
                    Print(extab + "Key Usage Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Usages:" + keyu.ToString());
                }
                else if (oid == X509Extensions.ExtendedKeyUsage.Id)
                {
                    ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext);



                    Print(extab + "Extended Key Usage Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Extended Key Usages:");
                    foreach (DerObjectIdentifier id in keyu.GetAllUsages())
                    {
                        Print(extab + "         " + id.Id);
                    }
                }
                else if (oid == X509Extensions.SubjectKeyIdentifier.Id)
                {
                    SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext);
                    Print(extab + "Subject Key Identifier Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Identifier:");
                    Print(keyu.GetKeyIdentifier(), extab + "         ");
                }
                else if (oid == X509Extensions.AuthorityKeyIdentifier.Id)
                {
                    AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext);
                    Print(extab + "Authority Key Identifier Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Identifier:");
                    Print(keyu.GetKeyIdentifier(), extab + "         ");
                }
                else if (oid == X509Extensions.SubjectAlternativeName.Id)
                {
                    Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                    GeneralNames keyu = GeneralNames.GetInstance(asn1Object);

                    Print(extab + "Subject Alternative Name Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     General Names:");

                    foreach (GeneralName gen in keyu.GetNames())
                    {
                        string tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }

                        Print(extab + "         " + tagname + " " + gen.Name);
                    }
                }
                else if (oid == X509Extensions.IssuerAlternativeName.Id)
                {
                    Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                    GeneralNames keyu = GeneralNames.GetInstance(asn1Object);

                    Print(extab + "Issuer Alternative Name Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     General Names:");

                    foreach (GeneralName gen in keyu.GetNames())
                    {
                        string tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }

                        Print(extab + "         " + tagname + " " + gen.Name);
                    }
                }
                else if (oid == X509Extensions.AuthorityInfoAccess.Id)
                {
                    AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext);
                    Print(extab + "Authority Information Access Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Access Descriptions:");
                    foreach (AccessDescription acc in keyu.GetAccessDescriptions())
                    {
                        Print(extab + "         Method:" + acc.AccessMethod.Id);
                        GeneralName gen     = acc.AccessLocation;
                        string      tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }
                        Print(extab + "         Access Location:" + tagname + "=" + gen.Name);
                    }
                }
                else if (oid == X509Extensions.SubjectInfoAccess.Id)
                {
                    AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext);
                    Print(extab + "Subject Information Access Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Access Descriptions:");
                    foreach (AccessDescription acc in keyu.GetAccessDescriptions())
                    {
                        Print(extab + "         Method:" + acc.AccessMethod.Id);
                        GeneralName gen     = acc.AccessLocation;
                        string      tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }
                        Print(extab + "         Access Location:" + tagname + "=" + gen.Name);
                    }
                }
                else if (oid == X509Extensions.CrlDistributionPoints.Id)
                {
                    Asn1Object   asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);
                    CrlDistPoint keyu       = CrlDistPoint.GetInstance(asn1Object);


                    Print(extab + "Crl Distribution Points Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Distribution Points:");
                    foreach (DistributionPoint acc in keyu.GetDistributionPoints())
                    {
                        if (acc.Reasons != null)
                        {
                            Print(extab + "         Reasons:" + acc.Reasons.GetString());
                        }
                        else
                        {
                            Print(extab + "         Reasons:Null");
                        }

                        if (acc.CrlIssuer != null)
                        {
                            Print(extab + "         Crl Issuer:");
                            foreach (GeneralName gen in acc.CrlIssuer.GetNames())
                            {
                                string tagname = "Dns Name:";
                                if (gen.TagNo == GeneralName.EdiPartyName)
                                {
                                    tagname = "Edi Party Name:";
                                }
                                else if (gen.TagNo == GeneralName.IPAddress)
                                {
                                    tagname = "IP Address:";
                                }
                                else if (gen.TagNo == GeneralName.OtherName)
                                {
                                    tagname = "Other Name:";
                                }
                                else if (gen.TagNo == GeneralName.RegisteredID)
                                {
                                    tagname = "Registered ID:";
                                }
                                else if (gen.TagNo == GeneralName.Rfc822Name)
                                {
                                    tagname = "Rfc822 Name:";
                                }
                                else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                                {
                                    tagname = "URI:";
                                }
                                else if (gen.TagNo == GeneralName.X400Address)
                                {
                                    tagname = "X400 Address:";
                                }
                                else if (gen.TagNo == GeneralName.DirectoryName)
                                {
                                    tagname = "Directory Name:";
                                }
                                Print(extab + "            " + tagname + ": " + gen.Name);
                            }
                        }
                        else
                        {
                            Print(extab + "         Crl Issuer:Null");
                        }
                        Print(extab + "         Distribution Point Name:");
                        if (acc.DistributionPointName.PointType == DistributionPointName.FullName)
                        {
                            GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name);
                            foreach (GeneralName gen in sgen.GetNames())
                            {
                                string tagname = "Dns Name:";
                                if (gen.TagNo == GeneralName.EdiPartyName)
                                {
                                    tagname = "Edi Party Name:";
                                }
                                else if (gen.TagNo == GeneralName.IPAddress)
                                {
                                    tagname = "IP Address:";
                                }
                                else if (gen.TagNo == GeneralName.OtherName)
                                {
                                    tagname = "Other Name:";
                                }
                                else if (gen.TagNo == GeneralName.RegisteredID)
                                {
                                    tagname = "Registered ID:";
                                }
                                else if (gen.TagNo == GeneralName.Rfc822Name)
                                {
                                    tagname = "Rfc822 Name:";
                                }
                                else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                                {
                                    tagname = "URI:";
                                }
                                else if (gen.TagNo == GeneralName.X400Address)
                                {
                                    tagname = "X400 Address:";
                                }
                                else if (gen.TagNo == GeneralName.DirectoryName)
                                {
                                    tagname = "Directory Name:";
                                }
                                Print(extab + "                " + tagname + " " + gen.Name);
                            }
                        }
                        else
                        {
                            Print(extab + "                Not Supported by OCT");
                        }
                    }
                }
            }
            // Signature
            Print("     Signature Algorithm: " + cer.SignatureAlgorithm.FriendlyName + " " + (CERT.GetSignature().Length * 8) + " bit");
            Print(CERT.GetSignature(), "        ");

            Print("     SHA1 Fingerprint : ");
            Print(Sha1(CERT.GetEncoded()), "        ");
            Print("     SHA224 Fingerprint : ");
            Print(Sha224(CERT.GetEncoded()), "        ");
            Print("     SHA256 Fingerprint : ");
            Print(Sha256(CERT.GetEncoded()), "        ");
            Print("     SHA384 Fingerprint : ");
            Print(Sha384(CERT.GetEncoded()), "        ");
            Print("     SHA512 Fingerprint : ");
            Print(Sha512(CERT.GetEncoded()), "        ");
            Print("     MD5 Fingerprint : ");
            Print(MD5(CERT.GetEncoded()), "        ");

            Print("Issuer Base64:" + Convert.ToBase64String(CERT.IssuerDN.GetDerEncoded()));
            Print("Subject Base64:" + Convert.ToBase64String(CERT.SubjectDN.GetDerEncoded()));
            Print("Serial Base64:" + Convert.ToBase64String(CERT.SerialNumber.ToByteArray()));
            if (outputfile == "stdout")
            {
                Console.Read();
            }
            else
            {
                str.Close();
            }
        }
        /// <summary>
        /// Qualification of extension by type
        /// </summary>
        /// <param name="asn1Encodable"></param>
        /// <returns></returns>
        private System.Security.Cryptography.X509Certificates.X509Extension QualificationExtension(Asn1Encodable asn1Encodable)
        {
            Asn1Sequence s = Asn1Sequence.GetInstance(asn1Encodable.ToAsn1Object());

            if (s.Count < 2 || s.Count > 3)
            {
                throw new ArgumentException("Bad sequence size: " + s.Count);
            }

            DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(s[0].ToAsn1Object());

            bool isCritical = s.Count == 3 &&
                              DerBoolean.GetInstance(s[1].ToAsn1Object()).IsTrue;

            Asn1OctetString octets = Asn1OctetString.GetInstance(s[s.Count - 1].ToAsn1Object());

            var extension = new System.Security.Cryptography.X509Certificates.X509Extension(new Oid(oid.Id), octets.GetOctets(), isCritical);

            var value = Asn1Object.FromByteArray(octets.GetOctets());

            switch (extension.Oid.Value)
            {
            case OidExtensions.SubjectKeyIdentifier:
                var spki = Asn1OctetString.GetInstance(value).GetOctets();
                extension = new X509SubjectKeyIdentifierExtension(spki, isCritical);
                break;

            case OidExtensions.ExtKeyUsage:
                var bcEKU           = ExtendedKeyUsage.GetInstance(value);
                var collectionFlags = new OidCollection();
                foreach (DerObjectIdentifier item in bcEKU.GetAllUsages())
                {
                    collectionFlags.Add(new Oid(item.Id));
                }
                extension = new X509EnhancedKeyUsageExtension(collectionFlags, isCritical);
                break;

            case OidExtensions.KeyUsage:
                var    bitString = DerBitString.GetInstance(value);
                byte[] data      = bitString.GetBytes();
                var    keyUsage  = data.Length == 1
                        ? data[0] & 0xff
                        : (data[1] & 0xff) << 8 | (data[0] & 0xff);
                extension = new X509KeyUsageExtension((X509KeyUsageFlags)keyUsage, isCritical);
                break;

            case OidExtensions.BasicConstraints:
                var bcBC = BasicConstraints.GetInstance(value);
                extension = new X509BasicConstraintsExtension(bcBC.IsCA(), true, bcBC.PathLenConstraint.IntValue, isCritical);
                break;

            case OidExtensions.TemplateV2:
                extension = new X509TemplateExtensionV2(octets.GetOctets(), isCritical);
                break;

            case OidExtensions.TemplateV1:
                extension = new X509TemplateExtensionV1(octets.GetOctets(), isCritical);
                break;

            default:
                break;
            }
            return(extension);
        }
示例#20
0
        /// <summary>
        /// Static method used to create a certificate and return as a .net object
        /// </summary>
        public static X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword,
                                              bool addtoStore = false)
        {
            // generate a key pair using RSA
            var generator = new RsaKeyPairGenerator();

            // keys have to be a minimum of 2048 bits for Azure
            generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            AsymmetricCipherKeyPair cerKp = generator.GenerateKeyPair();
            // get a copy of the private key
            AsymmetricKeyParameter privateKey = cerKp.Private;

            // create the CN using the name passed in and create a unique serial number for the cert
            var        certName = new X509Name("CN=" + name);
            BigInteger serialNo = BigInteger.ProbablePrime(120, new Random());

            // start the generator and set CN/DN and serial number and valid period
            var x509Generator = new X509V3CertificateGenerator();

            x509Generator.SetSerialNumber(serialNo);
            x509Generator.SetSubjectDN(certName);
            x509Generator.SetIssuerDN(certName);
            x509Generator.SetNotBefore(start);
            x509Generator.SetNotAfter(end);
            // add the server authentication key usage
            var keyUsage = new KeyUsage(KeyUsage.KeyEncipherment);

            x509Generator.AddExtension(X509Extensions.KeyUsage, false, keyUsage.ToAsn1Object());
            var extendedKeyUsage = new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth });

            x509Generator.AddExtension(X509Extensions.ExtendedKeyUsage, true, extendedKeyUsage.ToAsn1Object());
            // algorithm can only be SHA1 ??
            x509Generator.SetSignatureAlgorithm("sha1WithRSA");
            // Set the key pair
            x509Generator.SetPublicKey(cerKp.Public);
            X509Certificate certificate = x509Generator.Generate(cerKp.Private);

            // export the certificate bytes
            byte[] certStream = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12,
                                                                                      userPassword);

            // build the key parameter and the certificate entry
            var keyEntry = new AsymmetricKeyEntry(privateKey);
            var entry    = new X509CertificateEntry(certificate);
            // build the PKCS#12 store to encapsulate the certificate
            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.Build();
            // create a memorystream to hold the output
            var stream = new MemoryStream(2000);
            // create the individual store and set two entries for cert and key
            var store = new Pkcs12Store();

            store.SetCertificateEntry("Elastacloud Test Certificate", entry);
            store.SetKeyEntry("Elastacloud Test Certificate", keyEntry, new[] { entry });
            store.Save(stream, userPassword.ToCharArray(), new SecureRandom());

            // Create the equivalent C# representation
            var cert = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable);

            // if specified then this add this certificate to the store
            if (addtoStore)
            {
                AddToMyStore(cert);
            }

            return(cert);
        }
 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);
 }
        private X509Certificate MakeCertificate(AsymmetricCipherKeyPair subjectKeyPair, X509Name certificateSubject, AsymmetricCipherKeyPair rootKeyPair, X509Name rootSubject, bool isRootCertificate, bool addAuthorityKeyIdentifier)
        {
            X509Certificate x509Certificate;

            try
            {
                AsymmetricKeyParameter     @public  = subjectKeyPair.Public;
                AsymmetricKeyParameter     @private = rootKeyPair.Private;
                AsymmetricKeyParameter     asymmetricKeyParameter     = 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(certificateSubject);
                x509V3CertificateGenerator.SetPublicKey(@public);
                x509V3CertificateGenerator.SetSignatureAlgorithm(string.Concat(this.SignatureAlgorithm.ToString(), "Encryption"));
                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 });
                }
                bool keyUsageIsCritical = this.Extensions.KeyUsageIsCritical;
                if (isRootCertificate)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
                    extensionType     |= 6;
                    keyUsageIsCritical = true;
                }
                if (extensionType != 0)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.KeyUsage, keyUsageIsCritical, new KeyUsage(extensionType));
                }
                if (asn1EncodableVectors.Count > 0)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, this.Extensions.EnhancedKeyUsageIsCritical, ExtendedKeyUsage.GetInstance(new DerSequence(asn1EncodableVectors)));
                }
                x509V3CertificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(@public)));
                if (addAuthorityKeyIdentifier)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricKeyParameter)));
                }
                X509Certificate x509Certificate1 = x509V3CertificateGenerator.Generate(@private, this.GetSecureRandom());
                x509Certificate1.Verify(asymmetricKeyParameter);
                x509Certificate = x509Certificate1;
            }
            catch
            {
                throw;
            }
            return(x509Certificate);
        }
示例#23
0
        public static TimestampService Create(
            CertificateAuthority certificateAuthority,
            TimestampServiceOptions serviceOptions          = null,
            IssueCertificateOptions issueCertificateOptions = null)
        {
            if (certificateAuthority == null)
            {
                throw new ArgumentNullException(nameof(certificateAuthority));
            }

            serviceOptions = serviceOptions ?? new TimestampServiceOptions();

            if (issueCertificateOptions == null)
            {
                issueCertificateOptions = IssueCertificateOptions.CreateDefaultForTimestampService();
            }

            void customizeCertificate(X509V3CertificateGenerator generator)
            {
                generator.AddExtension(
                    X509Extensions.AuthorityInfoAccess,
                    critical: false,
                    extensionValue: new DerSequence(
                        new AccessDescription(AccessDescription.IdADOcsp,
                                              new GeneralName(GeneralName.UniformResourceIdentifier, certificateAuthority.OcspResponderUri.OriginalString)),
                        new AccessDescription(AccessDescription.IdADCAIssuers,
                                              new GeneralName(GeneralName.UniformResourceIdentifier, certificateAuthority.CertificateUri.OriginalString))));
                generator.AddExtension(
                    X509Extensions.AuthorityKeyIdentifier,
                    critical: false,
                    extensionValue: new AuthorityKeyIdentifierStructure(certificateAuthority.Certificate));
                generator.AddExtension(
                    X509Extensions.SubjectKeyIdentifier,
                    critical: false,
                    extensionValue: new SubjectKeyIdentifierStructure(issueCertificateOptions.KeyPair.Public));
                generator.AddExtension(
                    X509Extensions.BasicConstraints,
                    critical: true,
                    extensionValue: new BasicConstraints(cA: false));
                generator.AddExtension(
                    X509Extensions.KeyUsage,
                    critical: true,
                    extensionValue: new KeyUsage(KeyUsage.DigitalSignature));
                generator.AddExtension(
                    X509Extensions.ExtendedKeyUsage,
                    critical: true,
                    extensionValue: ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPTimeStamping)));
            }

            if (issueCertificateOptions.CustomizeCertificate == null)
            {
                issueCertificateOptions.CustomizeCertificate = customizeCertificate;
            }

            if (serviceOptions.IssuedCertificateNotBefore.HasValue)
            {
                issueCertificateOptions.NotBefore = serviceOptions.IssuedCertificateNotBefore.Value;
            }

            if (serviceOptions.IssuedCertificateNotAfter.HasValue)
            {
                issueCertificateOptions.NotAfter = serviceOptions.IssuedCertificateNotAfter.Value;
            }

            var certificate = certificateAuthority.IssueCertificate(issueCertificateOptions);
            var uri         = certificateAuthority.GenerateRandomUri();

            return(new TimestampService(certificateAuthority, certificate, issueCertificateOptions.KeyPair, uri, serviceOptions));
        }
        private static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var x500DistinguishedName = new X509Name("CN=" + subjectName);

            certificateGenerator.SetIssuerDN(x500DistinguishedName);
            certificateGenerator.SetSubjectDN(x500DistinguishedName);

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

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

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints,
                true,
                new BasicConstraints(false));
            certificateGenerator.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment));
            certificateGenerator.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                false,
                ExtendedKeyUsage.GetInstance(new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth)));

            // selfsign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // correcponding private key
            var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            // merge into X509Certificate2
            var x509 = new X509Certificate2(certificate.GetEncoded())
            {
                FriendlyName = $"{subjectName} self-signed"
            };

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return(x509);
        }
示例#25
0
文件: Key.cs 项目: mlfalke/ProDWebApp
        /// <summary>
        /// Static method used to create a certificate and return as a .net object
        /// </summary>

        public static X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword, bool addtoStore = false, string exportDirectory = @"Models\Encryption\Certificates\")
        {
            // generate a key pair using RSA
            var generator = new RsaKeyPairGenerator();

            // keys have to be a minimum of 2048 bits for Azure
            generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            AsymmetricCipherKeyPair cerKp = generator.GenerateKeyPair();
            // get a copy of the private key
            AsymmetricKeyParameter privateKey = cerKp.Private;


            // create the CN using the name passed in and create a unique serial number for the cert
            var        certName = new X509Name("CN=" + name);
            BigInteger serialNo = BigInteger.ProbablePrime(120, new Random());

            // start the generator and set CN/DN and serial number and valid period
            var x509Generator = new X509V3CertificateGenerator();

            x509Generator.SetSerialNumber(serialNo);
            x509Generator.SetSubjectDN(certName);
            x509Generator.SetIssuerDN(certName);
            x509Generator.SetNotBefore(start);
            x509Generator.SetNotAfter(end);
            // add the server authentication key usage
            var keyUsage = new KeyUsage(KeyUsage.KeyEncipherment);

            x509Generator.AddExtension(X509Extensions.KeyUsage, false, keyUsage.ToAsn1Object());
            var extendedKeyUsage = new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth });

            x509Generator.AddExtension(X509Extensions.ExtendedKeyUsage, true, extendedKeyUsage.ToAsn1Object());
            // algorithm can only be SHA1 ??


            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", cerKp.Private);

            // Set the key pair
            x509Generator.SetPublicKey(cerKp.Public);
            X509Certificate certificate = x509Generator.Generate(signatureFactory);


            // export the certificate bytes
            byte[] certStream = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12, userPassword);

            // build the key parameter and the certificate entry
            var keyEntry = new AsymmetricKeyEntry(privateKey);
            var entry    = new X509CertificateEntry(certificate);
            // build the PKCS#12 store to encapsulate the certificate
            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha256WithRsaEncryption);
            builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha256WithRsaEncryption);
            builder.Build();
            // create a memorystream to hold the output
            var stream = new MemoryStream(10000);
            // create the individual store and set two entries for cert and key
            var store = new Pkcs12Store();

            store.SetCertificateEntry("Created by Blockchain", entry);
            store.SetKeyEntry("Created by Blockchain", keyEntry, new[] { entry });
            store.Save(stream, userPassword.ToCharArray(), new SecureRandom());

            // Create the equivalent C# representation
            var cert = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable);

            // set up the PEM writer too
            if (exportDirectory != null)
            {
                var textWriter = new StringWriter();
                var pemWriter  = new PemWriter(textWriter);
                pemWriter.WriteObject(cerKp.Private, "DESEDE", userPassword.ToCharArray(), new SecureRandom());

                pemWriter.Writer.Flush();
                string privateKeyPem = textWriter.ToString();
                using (var writer = new StreamWriter(Path.Combine(exportDirectory, cert.Thumbprint + ".pem")))
                {
                    writer.WriteLine(privateKeyPem);
                }
                // also export the certs - first the .pfx
                byte[] privateKeyBytes = cert.Export(X509ContentType.Pfx, userPassword);
                using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".pfx"), FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writer.Write(privateKeyBytes, 0, privateKeyBytes.Length);
                }
                // also export the certs - then the .cer
                byte[] publicKeyBytes = cert.Export(X509ContentType.Cert);
                using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".cer"), FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writer.Write(publicKeyBytes, 0, publicKeyBytes.Length);
                }
            }

            // if specified then this add this certificate to the store
            if (addtoStore)
            {
                AddToMyStore(cert);
            }

            return(cert);
        }
        private static CertBundle MakeCertInternal(
            string issuerName, string subjectName,
            bool isCA,
            AsymmetricCipherKeyPair signerKey = null,
            AsymmetricCipherKeyPair certKey   = null,
            int pathLengthConstraint          = 0)
        {
            const int keyStrength              = 256;
            CryptoApiRandomGenerator   rg      = new CryptoApiRandomGenerator();
            SecureRandom               random  = new SecureRandom(rg);
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            // make a new ECC key pair.  The pubKey will go in the cert.  The private key may or may
            // not be used for signing, depending on whether the caller provides a signing key.
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new ECKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair newKey = keyPairGenerator.GenerateKeyPair();

            if (certKey != null)
            {
                newKey = certKey;
            }

            certGen.SetPublicKey(newKey.Public);
            BigInteger serialNumber = new BigInteger(new byte[] { 2, 3, 4 });

            certGen.SetSerialNumber(serialNumber);
            certGen.SetIssuerDN(new X509Name(issuerName));
            certGen.SetSubjectDN(new X509Name(subjectName));

            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore + new TimeSpan(365, 0, 0, 0);

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

            if (pathLengthConstraint != 0)
            {
                // then we want it to be a CA.  Using this constructor sets CA true AND sets the path length
                certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(pathLengthConstraint));
            }
            else
            {
                certGen.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                     ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPServerAuth)));
            };

            // Sign the cert
            var signingKey = (signerKey != null) ? signerKey : newKey;
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHECDSA", signingKey.Private, random);

            var certificate = certGen.Generate(signatureFactory);

            // and return the bundle
            var bundle = new CertBundle()
            {
                Certificate = certificate, KeyPair = newKey
            };

            return(bundle);
        }
示例#27
0
        public void CheckCertificate(
            int id,
            byte[]  cert)
        {
            Asn1Object seq  = Asn1Object.FromByteArray(cert);
            string     dump = Asn1Dump.DumpAsString(seq);

            X509CertificateStructure obj     = X509CertificateStructure.GetInstance(seq);
            TbsCertificateStructure  tbsCert = obj.TbsCertificate;

            if (!tbsCert.Subject.ToString().Equals(subjects[id - 1]))
            {
                Fail("failed subject test for certificate id " + id
                     + " got " + tbsCert.Subject.ToString());
            }

            if (tbsCert.Version >= 3)
            {
                X509Extensions ext = tbsCert.Extensions;
                if (ext != null)
                {
                    foreach (DerObjectIdentifier oid in ext.ExtensionOids)
                    {
                        X509Extension extVal = ext.GetExtension(oid);
                        Asn1Object    extObj = Asn1Object.FromByteArray(extVal.Value.GetOctets());

                        if (oid.Equals(X509Extensions.SubjectKeyIdentifier))
                        {
                            SubjectKeyIdentifier.GetInstance(extObj);
                        }
                        else if (oid.Equals(X509Extensions.KeyUsage))
                        {
                            KeyUsage.GetInstance(extObj);
                        }
                        else if (oid.Equals(X509Extensions.ExtendedKeyUsage))
                        {
                            ExtendedKeyUsage ku = ExtendedKeyUsage.GetInstance(extObj);

                            Asn1Sequence sq = (Asn1Sequence)ku.ToAsn1Object();
                            for (int i = 0; i != sq.Count; i++)
                            {
                                KeyPurposeID.GetInstance(sq[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.SubjectAlternativeName))
                        {
                            GeneralNames gn = GeneralNames.GetInstance(extObj);

                            Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object();
                            for (int i = 0; i != sq.Count; i++)
                            {
                                GeneralName.GetInstance(sq[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.IssuerAlternativeName))
                        {
                            GeneralNames gn = GeneralNames.GetInstance(extObj);

                            Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object();
                            for (int i = 0; i != sq.Count; i++)
                            {
                                GeneralName.GetInstance(sq[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.CrlDistributionPoints))
                        {
                            CrlDistPoint p = CrlDistPoint.GetInstance(extObj);

                            DistributionPoint[] points = p.GetDistributionPoints();
                            for (int i = 0; i != points.Length; i++)
                            {
                                // do nothing
                            }
                        }
                        else if (oid.Equals(X509Extensions.CertificatePolicies))
                        {
                            Asn1Sequence cp = (Asn1Sequence)extObj;

                            for (int i = 0; i != cp.Count; i++)
                            {
                                PolicyInformation.GetInstance(cp[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.AuthorityKeyIdentifier))
                        {
                            AuthorityKeyIdentifier.GetInstance(extObj);
                        }
                        else if (oid.Equals(X509Extensions.BasicConstraints))
                        {
                            BasicConstraints.GetInstance(extObj);
                        }
                        else
                        {
                            //Console.WriteLine(oid.Id);
                        }
                    }
                }
            }
        }
示例#28
0
        static void Main(string[] args)
        {
            PolicyInformation[] certPolicies = new PolicyInformation[2];
            certPolicies[0] = new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.2.1.11.5"));
            certPolicies[1] = new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.2.1.11.18"));

            var randomGenerator      = new CryptoApiRandomGenerator();
            var random               = new SecureRandom(randomGenerator);
            var certificateGenerator = new X509V3CertificateGenerator();
            //serial
            var serialNumber =
                BigIntegers.CreateRandomInRange(
                    BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);
            // sig alg

            const string signatureAlgorithm = "SHA1WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Subjects
            //   Time x = new Time();
            var subjectDN = new X509Name("CN=localhost, O=Arsslensoft, C=TN,surname=Idadi,givenname=Arsslen, uniqueidentifier=15002060,businesscategory=Production,initials=Hello, gender=male, placeofbirth=El Manar, pseudonym=Arsslinko, postaladdress=2076, countryofcitizenship=TN, countryofresidence=TN,telephonenumber=53299093");
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Validity
            var notBefore = DateTime.UtcNow.Date.Subtract(new TimeSpan(5, 0, 0));
            var notAfter  = notBefore.AddYears(2);

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

            // PKEY
            const int strength = 512;
            var       keyGenerationParameters = new KeyGenerationParameters(random, strength);

            //  var x=    new Al.Security.Crypto.Generators.DsaKeyPairGenerator();
            // X9ECParameters ecP = NistNamedCurves.GetByName("B-571");
            // ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
            // ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator("ECDSA");
            // //ECPA par = new DsaParametersGenerator();
            // //par.Init(2048, 100, random);
            // //ECKeyGenerationParameters pa = new ECKeyGenerationParameters(random, par.GenerateParameters());
            ////  var keyPairGenerator = new DHKeyPairGenerator();
            //  //DsaParametersGenerator par = new DsaParametersGenerator();
            //  //par.Init(2048, 100, random);
            //  //DsaKeyGenerationParameters pa = new DsaKeyGenerationParameters(random, par.GenerateParameters());
            // // keyPairGenerator.Init(pa);
            // keyPairGenerator.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
            //var keyPairGenerator = new DsaKeyPairGenerator();
            //DsaParametersGenerator par = new DsaParametersGenerator();
            //par.Init(1024, 100, random);
            //DsaKeyGenerationParameters pa = new DsaKeyGenerationParameters(random, par.GenerateParameters());
            //keyPairGenerator.Init(pa);
            //   KeyPair = keyPairGenerator.GenerateKeyPair();

            var keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            StreamReader            str     = new StreamReader("D:\\test.key");
            PemReader               pem     = new PemReader(str);
            AsymmetricCipherKeyPair keypair = (AsymmetricCipherKeyPair)pem.ReadObject();
            var subjectKeyPair = keypair;

            str.Close();
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // ext
            X509Extensions

            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                              new SubjectKeyIdentifierStructure(subjectKeyPair.Public));

            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(subjectKeyPair.Public));
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));
            // key usage
            certificateGenerator.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(KeyUsage.KeyAgreement | KeyUsage.DataEncipherment | KeyUsage.DigitalSignature));
            // extended key usage
            var usages = new[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth };
            ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(usages);

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, extendedKeyUsage);
            // Test Policy

            DerSequence seq = CreatePolicyInformationsSequence("http://www.arsslensoft.com", "Arsslensoft", "1.3.6.1.4.1.23823.1.1.1", "Test Notice");

            //  certificateGenerator.AddExtension(X509Extensions.CertificatePolicies, false, new DerSequence(certPolicies));

            // Authority access
            List <GeneralSubtree> ees = new List <GeneralSubtree>();

            ees.Add(new GeneralSubtree(new GeneralName(GeneralName.UniformResourceIdentifier, "http://www.google.com")));
            certificateGenerator.AddExtension(X509Extensions.NameConstraints, true, new NameConstraints(null, ees));

            certificateGenerator.AddExtension(X509Extensions.NetscapeComment, true, new DerVisibleString("NS COMMENT"));
            certificateGenerator.AddExtension(X509Extensions.NetscapeBaseUrl, true, new DerIA5String("http://www.google.com"));
            certificateGenerator.AddExtension(X509Extensions.InhibitAnyPolicy, true, new DerInteger(12));
// Policy constraints
            byte inhibit   = 12;
            byte explicitc = 12;

            //   certificateGenerator.AddExtension(X509Extensions.PolicyConstraints, false, new DerOctetSequence(new byte[] { 128, 1, explicitc, 129, 1, inhibit }));
            certificateGenerator.AddExtension(X509Extensions.NetscapeCertUsage, false, new KeyUsage(KeyUsage.KeyAgreement));

            certificateGenerator.AddExtension(X509Extensions.AuthorityInfoAccess, false, CreateAuthorityAccessInformationSequence("http://www.arsslensoft.com", null));
            // Subhect Issuer Alternative name
            GeneralName  altName        = new GeneralName(GeneralName.DnsName, "localhost");
            GeneralNames subjectAltName = new GeneralNames(altName);

            certificateGenerator.AddExtension(X509Extensions.IssuerAlternativeName, false, subjectAltName);
            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
            //   certificateGenerator.AddExtension(new DerObjectIdentifier("2.16.840.1.11730.29.53"), false, subjectAltName);
            //

            GeneralNames s;

            //CRL Distribution Points
            DistributionPointName distPointOne = new DistributionPointName(new GeneralNames(
                                                                               new GeneralName(GeneralName.UniformResourceIdentifier, "http://crl.somewebsite.com/master.crl")));
            GeneralNames gns = new GeneralNames(new GeneralName[] {
                new GeneralName(GeneralName.UniformResourceIdentifier, "ldap://crl.somewebsite.com/cn%3dSecureCA%2cou%3dPKI%2co%3dCyberdyne%2cc%3dUS?certificaterevocationlist;binary"), new GeneralName(GeneralName.Rfc822Name, "Arslen")
            });
            DistributionPointName distPointTwo = new DistributionPointName(gns);

            DistributionPoint[] distPoints = new DistributionPoint[2];
            distPoints[0] = new DistributionPoint(distPointOne, null, null);
            distPoints[1] = new DistributionPoint(distPointTwo, null, gns);

            IssuingDistributionPoint iss = new IssuingDistributionPoint(distPointOne, false, true, null, false, false);

            certificateGenerator.AddExtension(X509Extensions.IssuingDistributionPoint, false, iss);

            certificateGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, new CrlDistPoint(distPoints));

            // Biometric
            Asn1EncodableVector v = new Asn1EncodableVector();

            BiometricData bdat = new BiometricData(new TypeOfBiometricData(TypeOfBiometricData.HandwrittenSignature), new AlgorithmIdentifier(new DerObjectIdentifier("1.3.14.3.2.26")), new DerOctetString(new byte[] { 169, 74, 143, 229, 204, 177, 155, 166, 28, 76, 8, 115, 211, 145, 233, 135, 152, 47, 187, 211 }), new DerIA5String("http://www.google.com"));

            v.Add(bdat);
            v.Add(new BiometricData(new TypeOfBiometricData(TypeOfBiometricData.HandwrittenSignature), new AlgorithmIdentifier(new DerObjectIdentifier("1.3.14.3.2.26")), new DerOctetString(new byte[] { 169, 74, 143, 229, 204, 177, 155, 166, 28, 76, 8, 115, 211, 145, 233, 135, 152, 47, 187, 211 }), new DerIA5String("http://www.google.co")));
            certificateGenerator.AddExtension(X509Extensions.BiometricInfo, false, new DerSequenceOf(v));

            QCStatement st = new QCStatement(Rfc3739QCObjectIdentifiers.IdQcs);

            certificateGenerator.AddExtension(X509Extensions.QCStatements, false, st);
            //Al.Security.Pkcs.Pkcs10CertificationRequest c = new Al.Security.Pkcs.Pkcs10CertificationRequest(
            //certificateGenerator.AddExtension(X509Extensions.ReasonCode, false, ce);
            // test done
            certificateGenerator.AddExtension(X509Extensions.SubjectInfoAccess, false, CreateAuthorityAccessInformationSequence("http://www.arsslensoft.com", null));
            //// 2
            //TargetInformation ti = new Al.Security.Asn1.X509.TargetInformation(new Target[] { new Target(Target.Choice.Name, new GeneralName(GeneralName.UniformResourceIdentifier, "http://www.go.com")) });
            //certificateGenerator.AddExtension(X509Extensions.TargetInformation, false, new DerSequence(ti));
            // 3
            PrivateKeyUsagePeriod kup = new PrivateKeyUsagePeriod(DateTime.Now, DateTime.Now.AddYears(2));

            certificateGenerator.AddExtension(X509Extensions.PrivateKeyUsagePeriod, false, new DerSequence(kup));


            //generate
            var issuerKeyPair = subjectKeyPair;
            var certificate   = certificateGenerator.Generate(issuerKeyPair.Private, random);


            StreamWriter wstr      = new StreamWriter(Path.ChangeExtension("D:\\test.crt", ".pem"), false);
            PemWriter    pemWriter = new PemWriter(wstr);

            pemWriter.WriteObject(certificate);
            pemWriter.WriteObject(issuerKeyPair.Private);

            wstr.Flush();
            wstr.Close();

            //   System.Security.Cryptography.X509Certificates.X509Certificate x509_ = DotNetUtilities.ToX509Certificate(certificate.CertificateStructure);

            //File.WriteAllBytes(@"D:\\test.crt",   x509_.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12));
        }
示例#29
0
        /// <summary>
        /// Generate certificate request and private key file
        /// </summary>
        /// <param name="random"></param>
        /// <param name="subjectKeyPair"></param>
        /// <param name="subjectSerialNumber"></param>
        /// <param name="commonName"></param>
        /// <param name="subjectAlternativeNames"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="issuerSerialNumber"></param>
        /// <param name="isCertificateAuthority"></param>
        /// <param name="usages"></param>
        /// <param name="signatureAlgorithm"></param>
        /// <param name="countryCode"></param>
        /// <param name="stateOrProvinceName"></param>
        /// <param name="localityName"></param>
        /// <param name="organization"></param>
        /// <param name="arrccbKeyUsage"></param>
        /// <param name="arrExtendedKeyUsage"></param>
        /// <param name="outputPrivateKeyName"></param>
        /// <param name="outputCertReqFile"></param>
        private async void GenerateCertificate(SecureRandom random,
                                               AsymmetricCipherKeyPair subjectKeyPair,
                                               BigInteger subjectSerialNumber,
                                               string commonName,
                                               string[] subjectAlternativeNames,
                                               AsymmetricCipherKeyPair issuerKeyPair,
                                               BigInteger issuerSerialNumber,
                                               bool isCertificateAuthority,
                                               KeyPurposeID[] usages,
                                               string signatureAlgorithm,
                                               string countryCode,
                                               string stateOrProvinceName,
                                               string localityName,
                                               string organization,
                                               List <int> arrccbKeyUsage,
                                               List <string> arrExtendedKeyUsage,
                                               string outputPrivateKeyName,
                                               string outputCertReqFile)
        {
            #region Private Key
            IDictionary attrs = new Hashtable();
            attrs[X509Name.CN] = commonName;
            attrs[X509Name.C]  = countryCode;
            attrs[X509Name.ST] = stateOrProvinceName;
            attrs[X509Name.L]  = localityName;
            attrs[X509Name.O]  = organization;

            IList ord = new ArrayList();
            ord.Add(X509Name.CN);
            ord.Add(X509Name.C);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.L);
            ord.Add(X509Name.O);

            X509Name issuerDN = new X509Name(ord, attrs);

            try
            {
                using (TextWriter tw = new StreamWriter(outputPrivateKeyName))
                {
                    PemWriter pw = new PemWriter(tw);
                    pw.WriteObject(subjectKeyPair.Private);
                    tw.Flush();
                }

                tbOutputMessageBox.Text += "File with private key: " + outputPrivateKeyName + " sucessfully generated." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "ERROR creating certificate private key file (.key)" + "\n" + "Error: " + ex.Source + " " + ex.Message;
                tbOutputMessageBox.Foreground = bckForeground;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR creating certificate private key file (.key)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }
            #endregion Private Key

            #region Public Key - old
            //if (outputPublicKeyName != null)
            //{
            //    //SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public);
            //    //byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            //    //string serializedPublic = Convert.ToBase64String(serializedPublicBytes);

            //    ////StringBuilder publicKeyStrBuilder = new StringBuilder();
            //    ////PemWriter publicKeyPemWriter = new PemWriter(new StringWriter(publicKeyStrBuilder));
            //    ////publicKeyPemWriter.WriteObject(subjectKeyPair.Public);
            //    ////publicKeyPemWriter.Writer.Flush();

            //    ////string publicKey = publicKeyStrBuilder.ToString();
            //    try
            //    {
            //        var store = new Pkcs12Store();
            //        string friendlyName = certificate.SubjectDN.ToString();
            //        var certificateEntry = new X509CertificateEntry(certificate);
            //        store.SetCertificateEntry(friendlyName, certificateEntry);
            //        store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

            //        var stream = new MemoryStream();
            //        store.Save(stream, "password".ToCharArray(), random);

            //        //Verify that the certificate is valid.
            //        var convertedCertificate = new X509Certificate2(stream.ToArray(), "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            //        //Write the file.
            //        File.WriteAllBytes(outputPublicKeyName, stream.ToArray());

            //        File.WriteAllBytes(System.IO.Path.ChangeExtension(outputPublicKeyName, ".cer"), certificate.GetEncoded());

            //        //using (TextWriter tw = new StreamWriter(outputPublicKeyName))
            //        //{
            //        //    PemWriter pw = new PemWriter(tw);
            //        //    pw.WriteObject(subjectKeyPair.Public);
            //        //    tw.Flush();
            //        //}

            //        tbOutputMessageBox.Text += "File with private key: " + outputPublicKeyName + " sucessfully generated." + "\n";
            //    }
            //    catch (Exception ex)
            //    {
            //        var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //        await metroWindow.ShowMessageAsync("Info Warning",
            //             "ERROR creating certificate private key file (.key)" + "\n" +
            //             "Error: " + ex.Source + " " + ex.Message,
            //             MessageDialogStyle.Affirmative);
            //        return;
            //    }
            //}
            #endregion Public Key

            #region CSR - Certificate Request file (.csr)
            // BasicConstraints
            var extensions = new Dictionary <DerObjectIdentifier, Org.BouncyCastle.Asn1.X509.X509Extension>()
            {
                { X509Extensions.BasicConstraints,
                  new Org.BouncyCastle.Asn1.X509.X509Extension(true, new DerOctetString(new BasicConstraints(false))) }
            };
            DerOctetString tmp = new DerOctetString(new BasicConstraints(false));

            //KeyUsage
            if (arrccbKeyUsage.Count > 0)
            {
                int usage = 0;
                for (int i = 0; i < arrccbKeyUsage.Count; i++)
                {
                    usage = usage | arrccbKeyUsage[i];
                }
                KeyUsage keyUsage = new KeyUsage(usage);
                extensions.Add(X509Extensions.KeyUsage,
                               new Org.BouncyCastle.Asn1.X509.X509Extension(true, new DerOctetString(keyUsage)));
            }

            //ExtendedKeyUsage
            if (arrExtendedKeyUsage.Count > 0)
            {
                KeyPurposeID[] extendedKeyUsageArr = new KeyPurposeID[arrExtendedKeyUsage.Count];
                for (int i = 0; i < arrExtendedKeyUsage.Count; i++)
                {
                    if (KeyPurposeID.AnyExtendedKeyUsage.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.AnyExtendedKeyUsage;
                    }
                    else if (KeyPurposeID.IdKPServerAuth.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPServerAuth;
                    }
                    else if (KeyPurposeID.IdKPClientAuth.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPClientAuth;
                    }
                    else if (KeyPurposeID.IdKPCodeSigning.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPCodeSigning;
                    }
                    else if (KeyPurposeID.IdKPEmailProtection.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPEmailProtection;
                    }
                    else if (KeyPurposeID.IdKPIpsecEndSystem.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPIpsecEndSystem;
                    }
                    else if (KeyPurposeID.IdKPIpsecTunnel.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPIpsecTunnel;
                    }
                    else if (KeyPurposeID.IdKPIpsecUser.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPIpsecUser;
                    }
                    else if (KeyPurposeID.IdKPTimeStamping.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPTimeStamping;
                    }
                    else if (KeyPurposeID.IdKPOcspSigning.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPOcspSigning;
                    }
                }

                ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(extendedKeyUsageArr);
                Asn1OctetString  asn1ost          = new DerOctetString(extendedKeyUsage);

                extensions.Add(X509Extensions.ExtendedKeyUsage,
                               new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(extendedKeyUsage)));
            }

            //SubjectAlternativeName
            if (subjectAlternativeNames.Length > 0)
            {
                GeneralNames names = new GeneralNames(
                    subjectAlternativeNames.Select(n => new GeneralName(GeneralName.DnsName, n)).ToArray()
                    );

                extensions.Add(X509Extensions.SubjectAlternativeName,
                               new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(names)));
            }

            //SubjectKeyIdentifier
            extensions.Add(X509Extensions.SubjectKeyIdentifier,
                           new Org.BouncyCastle.Asn1.X509.X509Extension(false,
                                                                        new DerOctetString(new SubjectKeyIdentifierStructure(subjectKeyPair.Public))));

            ISignatureFactory sigFactory = new Asn1SignatureFactory(signatureAlgorithm, subjectKeyPair.Private);

            Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest(
                sigFactory,
                issuerDN,
                subjectKeyPair.Public,
                new DerSet(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(extensions)))),
                subjectKeyPair.Private);

            bool isOK = csr.Verify();
            if (isOK)
            {
                tbOutputMessageBox.Text += "File with certificate request : " + outputCertReqFile + " sucessfully generated." + "\n";

                requestFileNamePath           = outputCertReqFile;
                requestFileNamePrivateKeyPath = outputPrivateKeyName;
                btnContinue.IsEnabled         = true;
            }
            else
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with certificate request : " + outputCertReqFile + " DOES NOT generated sucessfully!!!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("ERROR",
                                                   "File with certificate request : " + outputCertReqFile + " DOES NOT generated sucessfully!!!",
                                                   MessageDialogStyle.Affirmative);

                return;
            }

            try
            {
                using (TextWriter tw = new StreamWriter(outputCertReqFile))
                {
                    PemWriter pw = new PemWriter(tw);
                    pw.WriteObject(csr);
                    tw.Flush();
                }

                tbOutputMessageBox.Text += "File with certificate request : " + outputCertReqFile + " sucessfully saved." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, file with certificate request : " + outputCertReqFile + " DOES NOT saved." + "\n";
                tbOutputMessageBox.Foreground = bckForeground;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR to save certificate reguest file (.csr)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }
            #endregion CSR
        }
        /// <summary>
        /// Make a new Alias Cert.  If refresh=false, a new DevID and Alias are created.  If refresh=true
        /// then just the Alias is created and re-certified using the stored DevID key.
        /// </summary>
        /// <param name="refresh"></param>
        /// <returns></returns>
        internal DeviceBundle MakeAliasCert(bool refresh, int fwidSeed)
        {
            DateTime now = DateTime.Now;

            byte[] fwid = Helpers.HashData(new byte[1] {
                (byte)fwidSeed
            }, 0, 1);

            const int keyStrength           = 256;
            CryptoApiRandomGenerator rg     = new CryptoApiRandomGenerator();
            SecureRandom             random = new SecureRandom(rg);
            KeyGenerationParameters  keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new ECKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            AsymmetricCipherKeyPair devIdKey = null;

            if (refresh)
            {
                devIdKey = (AsymmetricCipherKeyPair)Helpers.ReadPemObject(ToPath(Program.DeviceIDPrivate));
            }
            else
            {
                devIdKey = keyPairGenerator.GenerateKeyPair();
            }

            // test - remove
            var oids = new List <Object>()
            {
                X509Name.UnstructuredName
            };
            var values = new List <Object>()
            {
                "ljkljljklkjlkjlkjlkjlkjlkjlkjlkjlkjljklkjlkjlkjlkjljk"
            };
            X509Name name = new X509Name(oids, values);



            AsymmetricCipherKeyPair aliasKey = keyPairGenerator.GenerateKeyPair();

            // make a string name based on DevID public.  Note that the authoritative information
            // is encoded in the RIoT-extension: this is just for quick-and-dirty device identification.
            var pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(devIdKey.Public);

            byte[] pubEncoded      = pubInfo.GetDerEncoded();
            var    pubHashed       = Helpers.HashData(pubEncoded, 0, pubEncoded.Length);
            var    shortNameBytes  = Helpers.CopyArray(pubHashed, 0, 8);
            var    shortNameString = Helpers.Hexify(shortNameBytes);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
            var serialNumber = new byte[8];

            rg.NextBytes(serialNumber);
            serialNumber[0] &= 0x7F;
            certGen.SetSerialNumber(new BigInteger(serialNumber));
            // The important name-related stuff is encoded in the RIoT extension
            certGen.SetIssuerDN(new X509Name($"CN=[I]DevID:{shortNameString}, O=MSR_TEST, C=US"));
            // test REMOVE
            //certGen.SetSubjectDN(name);
            certGen.SetSubjectDN(new X509Name($"CN=[S]DevID:{shortNameString}, O=MSR_TEST, C=US"));
            certGen.SetNotBefore(now);
            certGen.SetNotAfter(now + new TimeSpan(365 * 10, 0, 0, 0, 0));
            certGen.SetPublicKey(aliasKey.Public);

            // Add the extensions (todo: not sure about KeyUsage.DigitalSiganture
            certGen.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                 ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPClientAuth)));
            certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature));
            AddRIoTExtension(certGen, fwid, devIdKey);

            // sign it
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHECDSA", devIdKey.Private, random);
            var certificate = certGen.Generate(signatureFactory);
            // and return the bundle
            DeviceBundle bundle = new DeviceBundle
            {
                AliasCert      = certificate,
                DeviceIDPublic = devIdKey.Public,
                AliasKeyPair   = aliasKey
            };

            // Just the AliasCert
            Helpers.WritePEMObject(ToPath(Program.AliasCert), bundle.AliasCert);
            // The Alias Key Pair
            Helpers.WritePEMObject(ToPath(Program.AliasKey), bundle.AliasKeyPair);
            // The encoded DevID
            Helpers.WritePEMObject(ToPath(Program.DeviceIDPublic), bundle.DeviceIDPublic);
            // DeviceIDPrivate (just for the update demo)
            Helpers.WritePEMObject(ToPath(Program.DeviceIDPrivate), devIdKey.Private);

            return(bundle);
        }