public string AddSignature(string PathSource, string PathTarget, string CertPath, string CertPass, int lx = 100, int ly = 100, int ux = 250, int uy = 150, int page = 1, bool Visible = true)
        {
            try
            {
                Org.BouncyCastle.Crypto.AsymmetricKeyParameter Akp   = null;
                Org.BouncyCastle.X509.X509Certificate[]        Chain = null;

                string alias = null;
                Org.BouncyCastle.Pkcs.Pkcs12Store pk12;


                pk12 = new Org.BouncyCastle.Pkcs.Pkcs12Store(new System.IO.FileStream(CertPath, System.IO.FileMode.Open, System.IO.FileAccess.Read), CertPass.ToCharArray());

                IEnumerable aliases = pk12.Aliases;
                foreach (string aliasTemp in aliases)
                {
                    alias = aliasTemp;
                    if (pk12.IsKeyEntry(alias))
                    {
                        break;
                    }
                }

                Akp = pk12.GetKey(alias).Key;
                Org.BouncyCastle.Pkcs.X509CertificateEntry[] ce = pk12.GetCertificateChain(alias);
                Chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length];
                for (int k = 0; k < ce.Length; ++k)
                {
                    Chain[k] = ce[k].Certificate;
                }

                iTextSharp.text.pdf.PdfReader              reader = new iTextSharp.text.pdf.PdfReader(PathSource);
                iTextSharp.text.pdf.PdfStamper             st     = iTextSharp.text.pdf.PdfStamper.CreateSignature(reader, new System.IO.FileStream(PathTarget, System.IO.FileMode.Create, System.IO.FileAccess.Write), '\0', null, true);
                iTextSharp.text.pdf.PdfSignatureAppearance sap    = st.SignatureAppearance;

                if (Visible == true)
                {
                    page = (page <1 || page> reader.NumberOfPages) ? 1 : page;
                    sap.SetVisibleSignature(new iTextSharp.text.Rectangle(lx, ly, ux, uy), page, null);
                }

                sap.CertificationLevel = iTextSharp.text.pdf.PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;

                // digital signature - http://itextpdf.com/examples/iia.php?id=222

                IExternalSignature es = new PrivateKeySignature(Akp, "SHA-256"); // "BC"
                MakeSignature.SignDetached(sap, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);

                st.Close();
                return("");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Esempio n. 2
0
        public static void Test()
        {
            string pfxLocation = @"D:\lol\certificate.pfx";

            pfxLocation = @"D:\username\Desktop\DesktopArchiv\20180329_Desktop\CORMailService\CORMailService\CORMailService\CORMailService_TemporaryKey.pfx";


            Org.BouncyCastle.Pkcs.Pkcs12Store store = null;

            using (System.IO.Stream pfxStream = System.IO.File.OpenRead(pfxLocation))
            {
                store = new Org.BouncyCastle.Pkcs.Pkcs12Store(pfxStream, "".ToCharArray());
            }

            System.Console.WriteLine(store);

            foreach (string alias in store.Aliases)
            {
                System.Console.WriteLine(alias);

                // https://7thzero.com/blog/bouncy-castle-convert-a-bouncycastle-asymmetrickeyentry-to-a-.ne
                if (store.IsKeyEntry((string)alias))
                {
                    Org.BouncyCastle.Pkcs.AsymmetricKeyEntry keyEntry = store.GetKey(alias);
                    System.Console.WriteLine(keyEntry);
                    AsymmetricKeyParameter privateKey = keyEntry.Key;
                    System.Console.WriteLine(privateKey.IsPrivate);
                } // End if (store.IsKeyEntry((string)alias))


                Org.BouncyCastle.Pkcs.X509CertificateEntry certEntry = store.GetCertificate(alias);
                Org.BouncyCastle.X509.X509Certificate      cert      = certEntry.Certificate;
                System.Console.WriteLine(cert);

                AsymmetricKeyParameter publicKey = cert.GetPublicKey();
                System.Console.WriteLine(publicKey);

                // Org.BouncyCastle.Pkcs.X509CertificateEntry[] chain = store.GetCertificateChain(alias);

                // System.Security.Cryptography.X509Certificates.X509Certificate2 cert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(cert.GetEncoded());
                // Org.BouncyCastle.Security.DotNetUtilities.ToX509Certificate(cert);

                System.Security.Cryptography.X509Certificates.X509Certificate2 cert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxLocation);
                // cert2.PrivateKey = null;

                if (cert2.HasPrivateKey)
                {
                    System.Console.WriteLine(cert2.PrivateKey);
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Imports certificates and private keys from the specified stream.
        /// </summary>
        /// <remarks>
        /// <para>Imports certificates and private keys from the specified pkcs12 stream.</para>
        /// </remarks>
        /// <param name="stream">The stream to import.</param>
        /// <param name="password">The password to unlock the stream.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="stream"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="password"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An error occurred reading the stream.
        /// </exception>
        public void Import(System.IO.Stream stream, string password)
        {
            if (stream == null)
            {
                throw new System.ArgumentNullException(nameof(stream));
            }

            if (password == null)
            {
                throw new System.ArgumentNullException(nameof(password));
            }

            Org.BouncyCastle.Pkcs.Pkcs12Store pkcs12 =
                new Org.BouncyCastle.Pkcs.Pkcs12Store(stream, password.ToCharArray());

            foreach (string alias in pkcs12.Aliases)
            {
                if (pkcs12.IsKeyEntry(alias))
                {
                    Org.BouncyCastle.Pkcs.X509CertificateEntry[] chain = pkcs12.GetCertificateChain(alias);
                    Org.BouncyCastle.Pkcs.AsymmetricKeyEntry     entry = pkcs12.GetKey(alias);

                    for (int i = 0; i < chain.Length; i++)
                    {
                        if (unique.Add(chain[i].Certificate))
                        {
                            certs.Add(chain[i].Certificate);
                        }
                    }

                    if (entry.Key.IsPrivate)
                    {
                        keys.Add(chain[0].Certificate, entry.Key);
                    }
                }
                else if (pkcs12.IsCertificateEntry(alias))
                {
                    Org.BouncyCastle.Pkcs.X509CertificateEntry entry = pkcs12.GetCertificate(alias);

                    if (unique.Add(entry.Certificate))
                    {
                        certs.Add(entry.Certificate);
                    }
                }
            }
        }
Esempio n. 4
0
        public async Task Save(CertificateInfo input)
        {
            var dest = PathForIdentifier(input.CommonName.Value);

            _log.Information("Copying certificate to the pfx folder {dest}", dest);
            try
            {
                var collection = new X509Certificate2Collection
                {
                    input.Certificate
                };
                collection.AddRange(input.Chain.ToArray());
                var ms      = new MemoryStream(collection.Export(X509ContentType.Pfx) !);
                var bcPfx   = new bc.Pkcs.Pkcs12Store(ms, Array.Empty <char>());
                var aliases = bcPfx.Aliases.OfType <string>().ToList();
                var key     = default(bc.Pkcs.AsymmetricKeyEntry);
                var chain   = default(bc.Pkcs.X509CertificateEntry[]);
                foreach (var alias in aliases)
                {
                    if (bcPfx.IsKeyEntry(alias))
                    {
                        key   = bcPfx.GetKey(alias);
                        chain = bcPfx.GetCertificateChain(alias);
                        break;
                    }
                }
                using var fs = new FileInfo(dest).OpenWrite();
                bcPfx        = new bc.Pkcs.Pkcs12Store();
                bcPfx.SetKeyEntry(input.CommonName.Value, key, chain);
                bcPfx.Save(fs, _password?.ToCharArray(), new bc.Security.SecureRandom());
            }
            catch (Exception ex)
            {
                _log.Error(ex, "Error copying certificate to pfx path");
            }
            input.StoreInfo.TryAdd(
                GetType(),
                new StoreInfo()
            {
                Name = PfxFileOptions.PluginName,
                Path = _path
            });
        }
Esempio n. 5
0
        public static X509Certificate2 OpenCertificate(string pfxPath, string contrasenia)
        {
            var ms = new MemoryStream(File.ReadAllBytes(pfxPath));

            var st = new Org.BouncyCastle.Pkcs.Pkcs12Store(ms, contrasenia.ToCharArray());

            var alias     = st.Aliases.Cast <string>().FirstOrDefault(p => st.IsCertificateEntry(p));
            var keyEntryX = st.GetCertificate(alias);

            var x509 = new X509Certificate2(DotNetUtilities.ToX509Certificate(keyEntryX.Certificate));

            alias = st.Aliases.Cast <string>().FirstOrDefault(p => st.IsKeyEntry(p));
            var keyEntry             = st.GetKey(alias);
            var intermediateProvider = (RSACryptoServiceProvider)DotNetUtilities.ToRSA((Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)keyEntry.Key);

            x509.PrivateKey = intermediateProvider;

            return(x509);
        }
Esempio n. 6
0
        } // End Sub WithMsPfx

        public static PfxData Read(string pfxFilePath, string password = "")
        {
            Org.BouncyCastle.Pkcs.Pkcs12Store store = null;

            using (System.IO.Stream pfxStream = System.IO.File.OpenRead(pfxFilePath))
            {
                store = new Org.BouncyCastle.Pkcs.Pkcs12Store(pfxStream, password.ToCharArray());
            }

            // System.Console.WriteLine(store);


            foreach (string alias in store.Aliases)
            {
                Org.BouncyCastle.Pkcs.X509CertificateEntry certEntry = store.GetCertificate(alias);
                Org.BouncyCastle.X509.X509Certificate      cert      = certEntry.Certificate;

                // Org.BouncyCastle.Crypto.AsymmetricKeyParameter publicKey = cert.GetPublicKey();
                // System.Console.WriteLine(publicKey);

                // https://7thzero.com/blog/bouncy-castle-convert-a-bouncycastle-asymmetrickeyentry-to-a-.ne
                if (store.IsKeyEntry(alias))
                {
                    Org.BouncyCastle.Pkcs.AsymmetricKeyEntry       keyEntry   = store.GetKey(alias);
                    Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = keyEntry.Key;

                    if (privateKey.IsPrivate)
                    {
                        return new PfxData()
                               {
                                   Certificate = cert,
                                   PrivateKey  = privateKey
                               }
                    }
                    ;
                } // End if (store.IsKeyEntry((string)alias))
            }     // Next alias

            return(null);
        } // End Sub Read
Esempio n. 7
0
        private (RsaPrivateCrtKeyParameters rsaPrivateKey, X509Certificate certificate) Extract(Stream stream, string password)
        {
            Org.BouncyCastle.Pkcs.Pkcs12Store p12Store = new Org.BouncyCastle.Pkcs.Pkcs12Store(stream, password.ToCharArray());
            string keyEntryAlias = p12Store.Aliases.Cast <string>().FirstOrDefault(t => p12Store.IsKeyEntry(t));

            Org.BouncyCastle.Pkcs.X509CertificateEntry x509CertEntry = p12Store.GetCertificate(keyEntryAlias);

            Org.BouncyCastle.Pkcs.AsymmetricKeyEntry keyEntry = p12Store.GetKey(keyEntryAlias);
            return(keyEntry.Key as RsaPrivateCrtKeyParameters, x509CertEntry.Certificate);
        }