Exemplo n.º 1
0
        void LoadCSRInfo(string csrfile)
        {
            X509Request req = null;

            using (var bio = BIO.File(csrfile, "r"))
                req = new X509Request(bio);
            CSReq = req;



            //ArrayList s = new ArrayList();
            //certificationRequestInfo = csri;
            //ArrayList oid = csri.Subject.GetOids();
            //ArrayList vals = csri.Subject.GetValues();

            Dictionary <string, string> xvals = new Dictionary <string, string>();

            foreach (string k in req.Subject.OneLine.Split('/'))
            {
                if (!string.IsNullOrEmpty(k))
                {
                    string[] val = k.Split('=');
                    if (!xvals.ContainsKey(val[0]))
                    {
                        xvals.Add(val[0], val[1]);
                    }
                }
            }

            x509NameBind bind = new x509NameBind();

            bind.Vals     = xvals;
            nameFrm1.bind = bind;
            nameFrm1.LoadNames();
        }
Exemplo n.º 2
0
        public void CanAddRequestExtensions()
        {
            var extList = new List <X509V3ExtensionValue> {
                new X509V3ExtensionValue("subjectAltName", false, "DNS:foo.com,DNS:bar.org"),
                new X509V3ExtensionValue("keyUsage", false, "cRLSign,keyCertSign"),
            };

            var start = DateTime.Now;
            var end   = start + TimeSpan.FromMinutes(10);

            using (var key = new CryptoKey(RSA.FromPrivateKey(new BIO(RSA_KEY))))
                using (var request = new X509Request(1, new X509Name("foo"), key))
                {
                    OpenSSL.Core.Stack <X509Extension> extensions = new OpenSSL.Core.Stack <X509Extension>();
                    foreach (var extValue in extList)
                    {
                        using (var ext = new X509Extension(request, extValue.Name, extValue.IsCritical, extValue.Value))
                        {
                            Console.WriteLine(ext);
                            extensions.Add(ext);
                        }
                    }

                    request.AddExtensions(extensions);

                    Assert.AreEqual(EXPECTED_CERT, request.PEM);
                }
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            Authorities();
            return;

            SimpleSerialNumber       seq = new SimpleSerialNumber();
            X509CertificateAuthority ca  = X509CertificateAuthority.SelfSigned(
                seq,
                new X509Name("CN=."),
                TimeSpan.FromDays(10)
                );

            Console.WriteLine(ca.Certificate);

            DSA         dsa = new DSA(new DSAParameters(512));
            CryptoKey   key = new CryptoKey(dsa);
            X509Request req = new X509Request(0, new X509Name("CN=com."), key);

            req.Sign(key, MessageDigest.DSS1);

            X509Certificate cert = ca.ProcessRequest(req, TimeSpan.FromDays(10));

            Console.WriteLine(cert);
            Console.WriteLine("CA Verified: " + cert.Verify(ca.Key));
            Console.WriteLine("Self Verified: " + cert.Verify(key));

            SimpleSerialNumber       serial2 = new SimpleSerialNumber();
            X509CertificateAuthority caSelf  = new X509CertificateAuthority(
                cert,
                key,
                serial2);

            X509Request req2    = cert.CreateRequest(key, MessageDigest.DSS1);
            X509Name    subject = req2.Subject;

            Console.WriteLine("Request1: " + req);
            Console.WriteLine("Request2: " + req2);

            X509Certificate cert2 = caSelf.ProcessRequest(req2, TimeSpan.FromDays(10));

            Console.WriteLine("Cert2: " + cert2);

            DH dh = new DH(128, 5);

            MessageDigestContext mdc = new MessageDigestContext(MessageDigest.DSS1);

            byte[] msg = dh.PublicKey;
            byte[] sig = mdc.Sign(msg, key);

            Console.WriteLine(dh);
            Console.WriteLine("DH P         : " + BitConverter.ToString(dh.P));
            Console.WriteLine("DH G         : " + BitConverter.ToString(dh.G));
            Console.WriteLine("DH Secret Key: " + BitConverter.ToString(dh.PrivateKey));
            Console.WriteLine("DH Public Key: " + BitConverter.ToString(msg));
            Console.WriteLine("DH Signature : " + BitConverter.ToString(sig));

            Console.WriteLine(mdc.Verify(msg, sig, key));
        }
Exemplo n.º 4
0
        public void CanCreateRequest()
        {
            DateTime  start = DateTime.Now;
            DateTime  end   = start + TimeSpan.FromMinutes(10);
            CryptoKey key   = new CryptoKey(new DSA(true));

            using (X509Certificate cert = new X509Certificate(101, "CN=localhost", "CN=Root", key, start, end)) {
                X509Request request = cert.CreateRequest(key, MessageDigest.DSS1);
                Assert.AreEqual(true, request.Verify(key));
            }
        }
Exemplo n.º 5
0
 public void ExportAsDer(Stream s)
 {
     using (var xr = new X509Request(Pem))
     {
         using (var bio = BIO.MemoryBuffer())
         {
             xr.Write_DER(bio);
             var arr = bio.ReadBytes((int)bio.BytesPending);
             s.Write(arr.Array, arr.Offset, arr.Count);
         }
     }
 }
Exemplo n.º 6
0
 public static void ConvertPemToDer(Stream source, Stream target)
 {
     using (var ts = new StreamReader(source))
     {
         using (var xr = new X509Request(ts.ReadToEnd()))
         {
             using (var bio = BIO.MemoryBuffer())
             {
                 xr.Write_DER(bio);
                 var arr = bio.ReadBytes((int)bio.BytesPending);
                 target.Write(arr.Array, arr.Offset, arr.Count);
             }
         }
     }
 }
Exemplo n.º 7
0
        public FileInfo SignCertFromRequest(Byte[] requestData, Boolean ca)
        {
            FileInfo file = null;

            using (BIO bio = new BIO(requestData))
                using (X509Request request = new X509Request(bio))
                {
                    file = new FileInfo(Path.Combine(certDir.FullName, request.Subject.Common + ".cer"));

                    using (X509Certificate certificate = RootCA.ProcessRequest(request, DateTime.Now.AddHours(-24), DateTime.Now + TimeSpan.FromDays(365), MessageDigest.SHA1))
                    {
                        if (ca)
                        {
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "basicConstraints", true, "CA:true"));
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "keyUsage", true, "critical, cRLSign, keyCertSign, digitalSignature"));
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "certificatePolicies", true, "2.5.29.32.0"));
                        }
                        else
                        {
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "basicConstraints", true, "CA:false"));
                        }

                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "issuerAltName", true, "issuer:copy"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "nsComment", true, "IAM Tester Generated Certificate"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectKeyIdentifier", true, "hash"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "authorityKeyIdentifier", true, "keyid,issuer:always"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectAltName", true, "DNS:" + request.Subject.Common));

                        certificate.Sign(RootCA.Key, MessageDigest.SHA1);

                        using (FileStream fs = new FileStream(file.FullName, FileMode.Create, FileAccess.ReadWrite))
                            using (BinaryWriter bw = new BinaryWriter(fs))
                                using (BIO bio2 = BIO.MemoryBuffer())
                                {
                                    certificate.Write(bio2);
                                    Byte[] certData = bio2.ReadBytes((Int32)bio2.NumberWritten).Array;
                                    bw.Write(certData);
                                    bw.Close();
                                }

                        //Para atualizar com o tamanho e outros dados do arquivo
                        file = new FileInfo(file.FullName);
                    }
                }

            return(file);
        }
Exemplo n.º 8
0
        X509Certificate CreateCertificate(X509CertificateAuthority ca, string name, Configuration cfg, string section)
        {
            var now    = DateTime.Now;
            var future = now + TimeSpan.FromDays(365);

            using (var subject = new X509Name(name))
                using (var rsa = new RSA())
                {
                    rsa.GenerateKeys(1024, BigNumber.One, null, null);
                    using (var key = new CryptoKey(rsa))
                    {
                        var request = new X509Request(1, subject, key);
                        var cert    = ca.ProcessRequest(request, now, future, cfg, section);
                        cert.PrivateKey = key;
                        return(cert);
                    }
                }
        }
        public void TestGenCSR()
        {
            var pem = File.ReadAllText("openssl-rsagen-privatekey.txt");
            var rsa = CryptoKey.FromPrivateKey(pem, null);
            //pem = File.ReadAllText("openssl-rsagen-publickey.txt");
            //rsa = CryptoKey.FromPublicKey(pem, null);

            var nam = new X509Name();

            nam.Common  = "FOOBAR";
            nam.Country = "US";



            var csr = new X509Request();

            csr.PublicKey = rsa;
            csr.Subject   = nam;
            csr.Sign(rsa, MessageDigest.SHA256);

            File.WriteAllText("openssl-requ-csr.txt", csr.PEM);
            using (var bioOut = BIO.MemoryBuffer())
            {
                csr.Write_DER(bioOut);
                var arr = bioOut.ReadBytes((int)bioOut.BytesPending);

                File.WriteAllBytes("openssl-requ-csr.der", arr.Array);
            }

            //using (var bioIn = BIO.MemoryBuffer())
            //{
            //    var pem2 = File.ReadAllText("openssl-requ-csr.txt");
            //    bioIn.Write(pem2);

            //    var csr = new X509Request()
            //    var x509 = new X509Certificate(bioIn);

            //}
        }
Exemplo n.º 10
0
 /// <summary>
 /// Support exporting CSR to <see cref="EncodingFormat.PEM">PEM</see>
 /// and <see cref="EncodingFormat.DER">DER</see> formats.
 /// </summary>
 public override void ExportCsr(Csr csr, EncodingFormat fmt, Stream target)
 {
     if (fmt == EncodingFormat.PEM)
     {
         var bytes = Encoding.UTF8.GetBytes(csr.Pem);
         target.Write(bytes, 0, bytes.Length);
     }
     else if (fmt == EncodingFormat.DER)
     {
         using (var xr = new X509Request(csr.Pem))
         {
             using (var bio = BIO.MemoryBuffer())
             {
                 xr.Write_DER(bio);
                 var arr = bio.ReadBytes((int)bio.BytesPending);
                 target.Write(arr.Array, arr.Offset, arr.Count);
             }
         }
     }
     else
     {
         throw new NotSupportedException("encoding format has not been implemented");
     }
 }
Exemplo n.º 11
0
 /// <summary>
 /// Support importing CSR from <see cref="EncodingFormat.PEM">PEM</see>
 /// and <see cref="EncodingFormat.DER">DER</see> formats.
 /// </summary>
 public override Csr ImportCsr(EncodingFormat fmt, Stream source)
 {
     if (fmt == EncodingFormat.PEM)
     {
         using (var r = new StreamReader(source))
         {
             using (var x509 = new X509Request(r.ReadToEnd()))
             {
                 var csr = new Csr(x509.PEM);
                 return(csr);
             }
         }
     }
     else if (fmt == EncodingFormat.DER)
     {
         // TODO: Managed OpenSSL Library has not implemented
         // d2i_X509_REQ_bio(...) routine yet
         throw new NotImplementedException("x509 CSR export to DER has not yet been implemented");
     }
     else
     {
         throw new NotSupportedException("unsupported encoding format");
     }
 }
Exemplo n.º 12
0
        void DoWork()
        {
            try
            {
                //var certificateGenerator = new X509V3CertificateGenerator();
                // Step 1
                if (nameFrm1.GetNames())
                {
                    X509Name subject = new X509Name();

                    // TODO FIX NAME FRM
                    int progress = 0;
                    int cur      = 0;
                    foreach (KeyValuePair <string, string> keyp in nameFrm1.bind.Vals)
                    {
                        progress = (int)((double)((cur / nameFrm1.bind.Vals.Count) * 100));
                        backgroundWorker1.ReportProgress(progress, 1);
                        subject.AddEntryByName(keyp.Key.ToUpper(), keyp.Value);
                        cur++;
                    }



                    backgroundWorker1.ReportProgress(100, 1);

                    // Step 2
                    progress = 0;
                    cur      = 0;

                    if (keyGenerationFrm1.GenerateKey())
                    {
                        Al.Security.CA.KeyGenerationBind keyb = keyGenerationFrm1.bind;
                        CryptoKey KeyPair = keyb.KeyPair;
                        CSReq = new X509Request(2, subject, KeyPair);
                        // CUSTOM SERIAL NUMBER
                        SimpleSerialNumber serial = null;

                        if (keyGenerationFrm1.serialnumber.Value != null && keyGenerationFrm1.serialnumber.Value != 0)
                        {
                            serial = new SimpleSerialNumber(keyGenerationFrm1.serialnumber.Value);
                        }



                        backgroundWorker1.ReportProgress(100, 2);

                        // STEP 3
                        if (!configbox.Checked)
                        {
                            ExtensionsWork();
                        }
                        Configuration config = new Configuration(Application.StartupPath + @"\ext.cfg");
                        backgroundWorker1.ReportProgress(100, 3);
                        DateTime notbe = nameFrm1.notbefore.Value;
                        DateTime vali  = nameFrm1.notafter.Value;
                        // STEP 4 SAVE
                        //generate
                        SimpleSerialNumber       caserial   = new SimpleSerialNumber(PFX.Certificate.SerialNumber);
                        X509CertificateAuthority ca         = new X509CertificateAuthority(PFX.Certificate, PFX.PrivateKey, caserial, config);
                        X509Certificate          signedCert = null;
                        if (serial != null)
                        {
                            signedCert = ca.ProcessRequest(serial, config, CSReq, DateTime.UtcNow, vali, keyb.SignatureAlgorithm);
                        }

                        else
                        {
                            signedCert = ca.ProcessRequest(config, CSReq, DateTime.UtcNow, vali, keyb.SignatureAlgorithm);
                        }

                        //     CertExportFrm cfrm = new CertExportFrm();
                        cfrm.certificate = signedCert;
                        cfrm.Key         = KeyPair;
                        //   cfrm.ShowDialog();

                        backgroundWorker1.ReportProgress(100, 4);
                    }
                    else
                    {
                        SelectTab(superTabItem5);
                    }
                }
                else
                {
                    SelectTab(superTabItem4);
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Exemplo n.º 13
0
        protected Csr GenerateCsr(CsrDetails csrDetails, RsaPrivateKey rsaKeyPair, string messageDigest = "SHA256")
        {
            var rsaKeys = CryptoKey.FromPrivateKey(rsaKeyPair.Pem, null);

            // Translate from our external form to our OpenSSL internal form
            // Ref:  https://www.openssl.org/docs/manmaster/crypto/X509_NAME_new.html
            var xn = new X509Name();

            if (!string.IsNullOrEmpty(csrDetails.CommonName /**/))
            {
                xn.Common = csrDetails.CommonName;                                                                  // CN;
            }
            if (!string.IsNullOrEmpty(csrDetails.Country /**/))
            {
                xn.Country = csrDetails.Country;                                                                     // C;
            }
            if (!string.IsNullOrEmpty(csrDetails.StateOrProvince /**/))
            {
                xn.StateOrProvince = csrDetails.StateOrProvince;                                                             // ST;
            }
            if (!string.IsNullOrEmpty(csrDetails.Locality /**/))
            {
                xn.Locality = csrDetails.Locality;                                                                    // L;
            }
            if (!string.IsNullOrEmpty(csrDetails.Organization /**/))
            {
                xn.Organization = csrDetails.Organization;                                                                // O;
            }
            if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit /**/))
            {
                xn.OrganizationUnit = csrDetails.OrganizationUnit;                                                            // OU;
            }
            if (!string.IsNullOrEmpty(csrDetails.Description /**/))
            {
                xn.Description = csrDetails.Description;                                                                 // D;
            }
            if (!string.IsNullOrEmpty(csrDetails.Surname /**/))
            {
                xn.Surname = csrDetails.Surname;                                                                     // S;
            }
            if (!string.IsNullOrEmpty(csrDetails.GivenName /**/))
            {
                xn.Given = csrDetails.GivenName;                                                                   // G;
            }
            if (!string.IsNullOrEmpty(csrDetails.Initials /**/))
            {
                xn.Initials = csrDetails.Initials;                                                                    // I;
            }
            if (!string.IsNullOrEmpty(csrDetails.Title /**/))
            {
                xn.Title = csrDetails.Title;                                                                       // T;
            }
            if (!string.IsNullOrEmpty(csrDetails.SerialNumber /**/))
            {
                xn.SerialNumber = csrDetails.SerialNumber;                                                                // SN;
            }
            if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier /**/))
            {
                xn.UniqueIdentifier = csrDetails.UniqueIdentifier;                                                            // UID;
            }
            var xr = new X509Request(0, xn, rsaKeys);

            if (csrDetails.AlternativeNames != null)
            {
                // Format the common name as the first alternative name
                var commonName = $"{EXT_SAN_PREFIX_DNS}:{xn.Common}";

                // Concat with all subsequent alternative names
                var altNames = commonName + string.Join("", csrDetails.AlternativeNames.Select(
                                                            x => $",{EXT_SAN_PREFIX_DNS}:{x}"));

                // Assemble and add the SAN extension value
                var extensions = new OpenSSL.Core.Stack <X509Extension>();
                extensions.Add(new X509Extension(xr, EXT_NAME_SAN, false, altNames));
                xr.AddExtensions(extensions);
            }

            var md = MessageDigest.CreateByName(messageDigest);

            xr.Sign(rsaKeys, md);
            using (var bio = BIO.MemoryBuffer())
            {
                xr.Write(bio);
                return(new Csr(bio.ReadString()));
            }
        }
Exemplo n.º 14
0
        public String SignCert(X509Name Name, Boolean ca, subjectAltName altNames, Boolean saveFile, DateTime?expirationDate)
        {
            String certData = "";

            FileInfo file = new FileInfo(Path.Combine(certDir.FullName, Name.Common + ".pfx"));

            using (CryptoKey key = CreateNewRSAKey(4096))
            {
                int version = 2; // Version 2 is X.509 Version 3
                using (X509Request request = new X509Request(version, Name, key))
                    using (X509Certificate certificate = RootCA.ProcessRequest(request, DateTime.Now.AddHours(-24), (expirationDate.HasValue ? expirationDate.Value : DateTime.Now + TimeSpan.FromDays(365)), MessageDigest.SHA1))
                    {
                        if (ca)
                        {
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "basicConstraints", true, "CA:true"));
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "keyUsage", true, "critical, cRLSign, keyCertSign, digitalSignature"));
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "certificatePolicies", true, "2.5.29.32.0"));
                        }
                        else
                        {
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "basicConstraints", true, "CA:false"));
                        }

                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "issuerAltName", true, "issuer:copy"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "nsComment", true, "SafeID - IAM Generated Certificate"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectKeyIdentifier", true, "hash"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "authorityKeyIdentifier", true, "keyid,issuer:always"));
                        //certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectAltName", true, "DNS:" + Name.Common));

                        if (altNames != null)
                        {
                            foreach (Uri u in altNames.Uri)
                            {
                                certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectAltName", true, "URI:" + u.AbsoluteUri.ToLower()));
                            }

                            foreach (String m in altNames.Mail)
                            {
                                certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectAltName", true, "email:" + m));
                            }

                            foreach (String s in altNames.Dns)
                            {
                                certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectAltName", true, "DNS:" + s));
                            }

                            foreach (String s in altNames.Text)
                            {
                                certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectAltName", true, "otherName:1.2.3.4;UTF8:" + s));
                            }
                        }

                        /*
                         * subjectAltName=email:copy,email:[email protected],URI:http://my.url.here/
                         * subjectAltName=IP:192.168.7.1
                         * subjectAltName=IP:13::17
                         * subjectAltName=email:[email protected],RID:1.2.3.4
                         * subjectAltName=otherName:1.2.3.4;UTF8:some other identifier*/


                        //certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "keyUsage", true, "nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment, encipherOnly, decipherOnly, keyAgreement"));
                        //certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "extendedKeyUsage", true, "clientAuth"));
                        //certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "crlDistributionPoints", true, "URI:http://ok/certEnroll/ok-ca.crl"));

                        certificate.Sign(RootCA.Key, MessageDigest.SHA1);

                        if (saveFile)
                        {
                            certData = BuildPKCS12AndSave(file.FullName, this.signedPassword, key, certificate);
                        }
                        else
                        {
                            certData = BuildPKCS12(this.signedPassword, key, certificate);
                        }
                    }
            }

            return(certData);
        }
Exemplo n.º 15
0
		public X509Certificate Authorize(X509Request request)
		{
			return this.ca.ProcessRequest(request, TimeSpan.FromDays(365));
		}
Exemplo n.º 16
0
		static void Main(string[] args)
		{
			Authorities();
			return;

			SimpleSerialNumber seq = new SimpleSerialNumber();
			X509CertificateAuthority ca = X509CertificateAuthority.SelfSigned(
				seq,
				new X509Name("CN=."),
				TimeSpan.FromDays(10)
			);

			Console.WriteLine(ca.Certificate);

			DSA dsa = new DSA(new DSAParameters(512));
			CryptoKey key = new CryptoKey(dsa);
			X509Request req = new X509Request(0, new X509Name("CN=com."), key);
			req.Sign(key, MessageDigest.DSS1);

			X509Certificate cert = ca.ProcessRequest(req, TimeSpan.FromDays(10));
			Console.WriteLine(cert);
			Console.WriteLine("CA Verified: " + cert.Verify(ca.Key));
			Console.WriteLine("Self Verified: " + cert.Verify(key));

			SimpleSerialNumber serial2 = new SimpleSerialNumber();
			X509CertificateAuthority caSelf = new X509CertificateAuthority(
				cert,
				key,
				serial2);

			X509Request req2 = cert.CreateRequest(key, MessageDigest.DSS1);
			X509Name subject = req2.Subject;
			Console.WriteLine("Request1: " + req);
			Console.WriteLine("Request2: " + req2);

			X509Certificate cert2 = caSelf.ProcessRequest(req2, TimeSpan.FromDays(10));
			Console.WriteLine("Cert2: " + cert2);

			DH dh = new DH(128, 5);

			MessageDigestContext mdc = new MessageDigestContext(MessageDigest.DSS1);
			byte[] msg = dh.PublicKey;
			byte[] sig = mdc.Sign(msg, key);

			Console.WriteLine(dh);
			Console.WriteLine("DH P         : " + BitConverter.ToString(dh.P));
			Console.WriteLine("DH G         : " + BitConverter.ToString(dh.G));
			Console.WriteLine("DH Secret Key: " + BitConverter.ToString(dh.PrivateKey));
			Console.WriteLine("DH Public Key: " + BitConverter.ToString(msg));
			Console.WriteLine("DH Signature : " + BitConverter.ToString(sig));

			Console.WriteLine(mdc.Verify(msg, sig, key));
		}
Exemplo n.º 17
0
        void DoWork()
        {
            try
            {
                // Step 1
                if (nameFrm1.GetNames())
                {
                    X509Name subject = new X509Name();

                    // TODO FIX NAME FRM
                    int progress = 0;
                    int cur      = 0;
                    foreach (KeyValuePair <string, string> keyp in nameFrm1.bind.Vals)
                    {
                        progress = (int)((double)((cur / nameFrm1.bind.Vals.Count) * 100));
                        backgroundWorker1.ReportProgress(progress, 1);
                        subject.AddEntryByName(keyp.Key.ToUpper(), keyp.Value);
                        cur++;
                    }

                    //    X509Name subjectDN = new X509Name(oids, values);



                    backgroundWorker1.ReportProgress(100, 1);

                    // Step 2
                    progress = 0;
                    cur      = 0;

                    if (keyGenerationFrm1.GenerateKey())
                    {
                        Al.Security.CA.KeyGenerationBind keyb = keyGenerationFrm1.bind;
                        CryptoKey KeyPair = keyb.KeyPair;

                        //        Al.Security.CA.KeyGenerationBind keyb = keyGenerationFrm1.bind;


                        backgroundWorker1.ReportProgress(100, 2);

                        //        // STEP 3

                        backgroundWorker1.ReportProgress(100, 3);

                        // STEP 4 SAVE

                        //generate
                        X509Request req     = null;
                        int         version = 2; // Version 2 is X.509 Version 3

                        req = new X509Request(version, subject, KeyPair);

                        cfrm.Key         = KeyPair;
                        cfrm.certificate = req;
                    }
                    else
                    {
                        SelectTab(superTabItem5);
                    }
                }
                else
                {
                    SelectTab(superTabItem4);
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            Configuration            cfg  = new Configuration("openssl.cnf");
            X509CertificateAuthority root = X509CertificateAuthority.SelfSigned(
                cfg,
                new SimpleSerialNumber(),
                "Root1",
                DateTime.Now,
                TimeSpan.FromDays(365));
            X509CertificateAuthority rogue = X509CertificateAuthority.SelfSigned(
                cfg,
                new SimpleSerialNumber(),
                "Rogue",
                DateTime.Now,
                TimeSpan.FromDays(365));

            Identity        comId   = new Identity(new CryptoKey(new DSA(true)));
            X509Request     comReq  = comId.CreateRequest("com");
            X509Certificate comCert = root.ProcessRequest(comReq, DateTime.Now, DateTime.Now + TimeSpan.FromDays(365));

            if (!comCert.Verify(root.Key))
            {
                Console.WriteLine("Invalid com cert");
            }
            X509CertificateAuthority com = new X509CertificateAuthority(
                comCert,
                comId.PrivateKey,
                new SimpleSerialNumber(),
                cfg);

            Identity        id1   = new Identity(new CryptoKey(new DSA(true)));
            X509Request     req1  = id1.CreateRequest("1");
            X509Certificate cert1 = com.ProcessRequest(
                req1,
                DateTime.Now,
                DateTime.Now + TimeSpan.FromDays(365));

            Identity        id2   = new Identity(new CryptoKey(new DSA(true)));
            X509Request     req2  = id2.CreateRequest("2");
            X509Certificate cert2 = rogue.ProcessRequest(
                req2,
                DateTime.Now,
                DateTime.Now + TimeSpan.FromDays(365));

            X509Store store = new X509Store();

            store.AddTrusted(root.Certificate);
            store.AddUntrusted(root.Certificate);
            store.AddUntrusted(com.Certificate);

            string error;

            if (store.Verify(cert1, out error))
            {
                Console.WriteLine("cert1 OK");
            }
            else
            {
                Console.WriteLine("cert1: " + error);
            }

            store.AddUntrusted(rogue.Certificate);
            if (store.Verify(cert2, out error))
            {
                Console.WriteLine("cert2 OK");
            }
            else
            {
                Console.WriteLine("cert2: " + error);
            }

            //Console.WriteLine("root:");
            Console.WriteLine(root.Certificate);
            //Console.WriteLine("com:");
            Console.WriteLine(com.Certificate);
            //Console.WriteLine("rogue:");
            Console.WriteLine(rogue.Certificate);
            //Console.WriteLine("id1:");
            Console.WriteLine(cert1);
            //Console.WriteLine("id2:");
            Console.WriteLine(cert2);
        }
Exemplo n.º 19
0
        private Csr GenerateCsr(CsrDetails csrDetails, RsaPrivateKey rsaKeyPair, string messageDigest = "SHA256")
        {
            var rsaKeys = CryptoKey.FromPrivateKey(rsaKeyPair.Pem, null);

            // Translate from our external form to our OpenSSL internal form
            // Ref:  https://www.openssl.org/docs/manmaster/crypto/X509_NAME_new.html
            var xn = new X509Name();

            if (!string.IsNullOrEmpty(csrDetails.CommonName /**/))
            {
                xn.Common = csrDetails.CommonName;                                                                  // CN;
            }
            if (!string.IsNullOrEmpty(csrDetails.Country /**/))
            {
                xn.Country = csrDetails.Country;                                                                     // C;
            }
            if (!string.IsNullOrEmpty(csrDetails.StateOrProvince /**/))
            {
                xn.StateOrProvince = csrDetails.StateOrProvince;                                                             // ST;
            }
            if (!string.IsNullOrEmpty(csrDetails.Locality /**/))
            {
                xn.Locality = csrDetails.Locality;                                                                    // L;
            }
            if (!string.IsNullOrEmpty(csrDetails.Organization /**/))
            {
                xn.Organization = csrDetails.Organization;                                                                // O;
            }
            if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit /**/))
            {
                xn.OrganizationUnit = csrDetails.OrganizationUnit;                                                            // OU;
            }
            if (!string.IsNullOrEmpty(csrDetails.Description /**/))
            {
                xn.Description = csrDetails.Description;                                                                 // D;
            }
            if (!string.IsNullOrEmpty(csrDetails.Surname /**/))
            {
                xn.Surname = csrDetails.Surname;                                                                     // S;
            }
            if (!string.IsNullOrEmpty(csrDetails.GivenName /**/))
            {
                xn.Given = csrDetails.GivenName;                                                                   // G;
            }
            if (!string.IsNullOrEmpty(csrDetails.Initials /**/))
            {
                xn.Initials = csrDetails.Initials;                                                                    // I;
            }
            if (!string.IsNullOrEmpty(csrDetails.Title /**/))
            {
                xn.Title = csrDetails.Title;                                                                       // T;
            }
            if (!string.IsNullOrEmpty(csrDetails.SerialNumber /**/))
            {
                xn.SerialNumber = csrDetails.SerialNumber;                                                                // SN;
            }
            if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier /**/))
            {
                xn.UniqueIdentifier = csrDetails.UniqueIdentifier;                                                            // UID;
            }
            var xr = new X509Request(0, xn, rsaKeys);
            var md = MessageDigest.CreateByName(messageDigest);

            xr.Sign(rsaKeys, md);
            using (var bio = BIO.MemoryBuffer())
            {
                xr.Write(bio);
                return(new Csr(bio.ReadString()));
            }
        }
Exemplo n.º 20
0
 public X509Certificate Authorize(X509Request request)
 {
     return(this.ca.ProcessRequest(request, TimeSpan.FromDays(365)));
 }