Esempio n. 1
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);
                }
        }
Esempio 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);
            }
        }
Esempio n. 3
0
        public override void ExportArchive(PrivateKey pk, IEnumerable <Crt> certs, ArchiveFormat fmt, Stream target, string password = "")
        {
            var rsaPk = pk as RsaPrivateKey;

            if (rsaPk == null)
            {
                throw new NotSupportedException("unsupported private key type");
            }

            if (fmt == ArchiveFormat.PKCS12)
            {
                var x509Arr = certs.Select(x =>
                {
                    using (var bio = BIO.MemoryBuffer())
                    {
                        bio.Write(x.Pem);
                        return(new X509Certificate(bio));
                    }
                }).ToArray();

                using (var key = CryptoKey.FromPrivateKey(rsaPk.Pem, null))
                {
                    var caStack = new OpenSSL.Core.Stack <X509Certificate>();
                    for (int i = 1; i < x509Arr.Length; ++i)
                    {
                        caStack.Add(x509Arr[i]);
                    }

                    using (var pfx = new PKCS12(password == string.Empty ? null : password, key, x509Arr[0], caStack))
                    {
                        using (var bio = BIO.MemoryBuffer())
                        {
                            pfx.Write(bio);
                            var count = (int)bio.BytesPending;
                            var array = bio.ReadBytes(count);
                            target.Write(array.Array, 0, count);
                        }
                    }
                }

                foreach (var x in x509Arr)
                {
                    x.Dispose();
                }
            }
            else
            {
                throw new NotSupportedException("unsupported archive format");
            }
        }
Esempio n. 4
0
            /// <summary>
            /// Converts a certificate and private key to a PKCS#12 (.PFX) file.
            /// </summary>
            public static void ConvertToPfx(Stream keyPemSource, Stream crtPemSource, Stream isrPemSource, Stream pfxTarget)
            {
                using (BIO keyBio = BIO.MemoryBuffer(),
                       crtBio = BIO.MemoryBuffer(),
                       isrBio = BIO.MemoryBuffer())
                {
                    using (var ms = new MemoryStream())
                    {
                        keyPemSource.CopyTo(ms);
                        keyBio.Write(ms.ToArray());
                    }
                    using (var ms = new MemoryStream())
                    {
                        crtPemSource.CopyTo(ms);
                        crtBio.Write(ms.ToArray());
                    }
                    using (var ms = new MemoryStream())
                    {
                        isrPemSource.CopyTo(ms);
                        isrBio.Write(ms.ToArray());
                    }

                    using (var key = CryptoKey.FromPrivateKey(keyBio, null))
                    {
                        using (var crt = new X509Certificate(crtBio))
                        {
                            using (var isr = new X509Certificate(isrBio))
                            {
                                var isrStack = new OpenSSL.Core.Stack <X509Certificate>();
                                isrStack.Add(isr);

                                using (var pfx = new PKCS12(null, key, crt, isrStack))
                                {
                                    using (var pfxBio = BIO.MemoryBuffer())
                                    {
                                        pfx.Write(pfxBio);
                                        var arr = pfxBio.ReadBytes((int)pfxBio.BytesPending);
                                        pfxTarget.Write(arr.Array, arr.Offset, arr.Count);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        /// <summary>
        /// Writes the specified Certificate and Crypto key out to the file defined in the fileName parameter. This
        /// file is protected with the specified password. The password is optional.
        /// </summary>
        /// <param name="fileName">The file name and path of the pfx file to be created.</param>
        /// <param name="password">The password to be put on the pfx file if any.</param>
        /// <param name="cryptoKey">The CryptoKey containing the private key that belongs to the certificate parameter.</param>
        /// <param name="certificate">The certificate to write to file.</param>
        public static void WritePfxToFile(string fileName, string password, CryptoKey cryptoKey, X509Certificate certificate)
        {
            if (cryptoKey == null)
            {
                throw new ArgumentNullException("cryptoKey", "CryptoKey is null");
            }
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate", "certificate is null");
            }

            using (var bio = FileHelpers.Write(fileName))
                using (var caStack = new OpenSSL.Core.Stack <X509Certificate>())
                    using (var pfx = new PKCS12(password, cryptoKey, certificate, caStack))
                    {
                        pfx.Write(bio);
                    }
        }
Esempio n. 6
0
        public void TestWithoutCfg()
        {
            BigNumber bn = 0x10001;
            CryptoKey key;

            using (RSA rsa = new RSA()) {
                rsa.GenerateKeys(2048, bn, OnGenerator, null);
                key = new CryptoKey(rsa);
                // rsa is assigned, we no longer need this instance
            }

            X509V3ExtensionList extList = new X509V3ExtensionList();

            extList.Add(new X509V3ExtensionValue("subjectKeyIdentifier", false, "hash"));
            extList.Add(new X509V3ExtensionValue("authorityKeyIdentifier", false, "keyid:always,issuer:always"));
            extList.Add(new X509V3ExtensionValue("basicConstraints", true, "critical,CA:true"));
            extList.Add(new X509V3ExtensionValue("keyUsage", false, "cRLSign,keyCertSign"));

            using (X509CertificateAuthority root = X509CertificateAuthority.SelfSigned(
                       new SimpleSerialNumber(),
                       key,
                       MessageDigest.SHA1,
                       "Root1",
                       DateTime.Now,
                       TimeSpan.FromDays(365),
                       extList)) {
                Console.WriteLine(root.Certificate);
                // Iterate the extensions
                Console.WriteLine("X509v3 Extensions:");
                using (OpenSSL.Core.Stack <X509Extension> ext_stack = root.Certificate.Extensions) {
                    foreach (X509Extension ext in ext_stack)
                    {
                        Console.WriteLine("Name:{0}, IsCritical:{1}, Value:{2}", ext.Name, ext.IsCritical, ext);
                    }
                }
            }
        }
Esempio n. 7
0
        private void buttonX1_Click(object sender, EventArgs e)
        {
            try
            {
                superValidator1.SetValidator1(textBoxX1, null);
                superValidator1.SetValidator1(c, null);
                if (pem.Checked)
                {
                    //       superValidator1.SetValidator1(textBoxX1, new DevComponents.DotNetBar.Validator.RequiredFieldValidator("Password is required for Key Encryption"));
                    superValidator1.SetValidator1(c, new DevComponents.DotNetBar.Validator.RequiredFieldValidator("Cipher is required for Key Encryption"));
                }
                //else if(pfx.Checked)
                //    superValidator1.SetValidator1(textBoxX1, new DevComponents.DotNetBar.Validator.RequiredFieldValidator("Password is required for Key Encryption"));

                if (superValidator1.Validate())
                {
                    superValidator1.SetValidator1(textBoxX1, null);
                    superValidator1.SetValidator1(c, null);
                    string devpath = "";
                    if (MainForm.cai != null)
                    {
                        if (MainForm.cai.DevPath != null)
                        {
                            devpath = MainForm.cai.DevPath;
                        }
                    }
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Origisign Temp Certificate|*.ogtc";
                    if (devpath != "")
                    {
                        sfd.InitialDirectory = devpath;
                    }

                    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        FileName = sfd.FileName;
                        //if (pkcs7.Checked)
                        //    File.WriteAllBytes(Path.ChangeExtension(FileName, ".p7b"), certificate.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs7));


                        if (pfx.Checked)
                        {
                            using (var bio = BIO.File(Path.ChangeExtension(FileName, ".pfx"), "w"))
                            {
                                OpenSSL.Core.Stack <X509Certificate> caStack = new OpenSSL.Core.Stack <X509Certificate>();
                                //    caStack.Add(certificate);

                                using (var pfx12 = new PKCS12(textBoxX1.Text, Key, certificate, caStack))
                                    pfx12.Write(bio);
                            }
                        }
                        if (cert.Checked)
                        {
                            using (var bio = BIO.File(Path.ChangeExtension(FileName, ".cer"), "w"))
                                certificate.Write(bio);
                        }
                        if (pem.Checked)
                        {
                            ComboItem ci = (ComboItem)c.SelectedItem;

                            using (var bio = BIO.File(Path.ChangeExtension(FileName, ".key"), "w"))
                                Key.WritePrivateKey(bio, (Cipher)ci.Value, textBoxX1.Text);
                        }



                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.Message, "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
        }
Esempio n. 8
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()));
            }
        }
Esempio n. 9
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);

            if (csrDetails.AlternativeNames.Count > 0)
            {
                OpenSSL.Core.Stack <X509Extension> extensions = new OpenSSL.Core.Stack <X509Extension>();
                // Add the common name as the first alternate
                string altNames = "DNS:" + xn.Common;
                foreach (var name in csrDetails.AlternativeNames)
                {
                    altNames += ", DNS:" + name;
                }
                extensions.Add(new X509Extension(xr, "subjectAltName", 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()));
            }
        }
Esempio n. 10
0
            /// <summary>
            /// Converts a certificate and private key to a PKCS#12 (.PFX) file.
            /// </summary>
            public static void ConvertToPfx(Stream keyPemSource, Stream crtPemSource, Stream isrPemSource, Stream pfxTarget)
            {
                using (BIO keyBio = BIO.MemoryBuffer(),
                        crtBio = BIO.MemoryBuffer(),
                        isrBio = BIO.MemoryBuffer())
                {
                    using (var ms = new MemoryStream())
                    {
                        keyPemSource.CopyTo(ms);
                        keyBio.Write(ms.ToArray());
                    }
                    using (var ms = new MemoryStream())
                    {
                        crtPemSource.CopyTo(ms);
                        crtBio.Write(ms.ToArray());
                    }
                    using (var ms = new MemoryStream())
                    {
                        isrPemSource.CopyTo(ms);
                        isrBio.Write(ms.ToArray());
                    }

                    using (var key = CryptoKey.FromPrivateKey(keyBio, null))
                    {
                        using (var crt = new X509Certificate(crtBio))
                        {
                            using (var isr = new X509Certificate(isrBio))
                            {
                                var isrStack = new OpenSSL.Core.Stack<X509Certificate>();
                                isrStack.Add(isr);

                                using (var pfx = new PKCS12(null, key, crt, isrStack))
                                {
                                    using (var pfxBio = BIO.MemoryBuffer())
                                    {
                                        pfx.Write(pfxBio);
                                        var arr = pfxBio.ReadBytes((int)pfxBio.BytesPending);
                                        pfxTarget.Write(arr.Array, arr.Offset, arr.Count);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        /// <summary>
        /// Writes the specified Certificate and Crypto key out to the file defined in the fileName parameter. This
        /// file is protected with the specified password. The password is optional.
        /// </summary>
        /// <param name="fileName">The file name and path of the pfx file to be created.</param>
        /// <param name="password">The password to be put on the pfx file if any.</param>
        /// <param name="cryptoKey">The CryptoKey containing the private key that belongs to the certificate parameter.</param>
        /// <param name="certificate">The certificate to write to file.</param>
        public static void WritePfxToFile(string fileName, string password, CryptoKey cryptoKey, X509Certificate certificate)
        {
            if (cryptoKey == null)
            {
                throw new ArgumentNullException("cryptoKey", "CryptoKey is null");
            }
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate", "certificate is null");
            }

            using (var bio = FileHelpers.Write(fileName))
            using (var caStack = new OpenSSL.Core.Stack<X509Certificate>())
            using (var pfx = new PKCS12(password, cryptoKey, certificate, caStack))
            {
                pfx.Write(bio);
            }
        }