private static X509Certificate[] constructChain(Pkcs12Store pkcs12Store, string alias)
        {
            var certificateChains = pkcs12Store.GetCertificateChain(alias);
            var chain             = new X509Certificate[certificateChains.Length];

            for (var k = 0; k < certificateChains.Length; ++k)
            {
                chain[k] = certificateChains[k].Certificate;
            }

            return(chain);
        }
        public Certificado(string rutaCompletaDelPfx, string claveDelPfx = null)
        {
            using (var file = File.OpenRead(rutaCompletaDelPfx))
            {
                var password = claveDelPfx?.ToCharArray() ?? new char[] { /* password en blanco */ };
                var store    = new Pkcs12Store(file, password);
                var alias    = GetCertificateAlias(store);

                Key   = store.GetKey(alias).Key;
                Chain = store.GetCertificateChain(alias).Select(x => x.Certificate).ToArray();
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            Parser.Default.ParseArguments <Options>(args).WithParsed <Options>(options =>
            {
                string keystore = options.SignatureCertificate;
                char[] password = options.SignaturePassword.ToCharArray();

                Pkcs12Store pkcs12Store = new Pkcs12Store(new FileStream(keystore, FileMode.Open, FileAccess.Read), password);
                string keyAlias         = null;

                foreach (object alias in pkcs12Store.Aliases)
                {
                    keyAlias = (string)alias;

                    if (pkcs12Store.IsKeyEntry(keyAlias))
                    {
                        break;
                    }
                }

                ICipherParameters key = pkcs12Store.GetKey(keyAlias).Key;

                X509CertificateEntry[] certificateEntry = pkcs12Store.GetCertificateChain(keyAlias);
                X509Certificate[] certificate           = new X509Certificate[certificateEntry.Length];

                for (int i = 0; i < certificateEntry.Length; ++i)
                {
                    certificate[i] = certificateEntry[i].Certificate;
                }

                string srcPdf  = options.SrcPdf;
                string destPdf = System.IO.Path.GetTempFileName();

                PdfReader pdfReader = new PdfReader(srcPdf);
                PdfSigner pdfSigner = new PdfSigner(pdfReader, new FileStream(destPdf, FileMode.Create), new StampingProperties());

                PdfSignatureAppearance appearance = pdfSigner.GetSignatureAppearance();

                appearance
                .SetLayer2Text(options.SignatureText)
                .SetPageRect(new Rectangle(options.SignatureRectangleX, options.SignatureRectangleY, options.SignatureRectangleWidth, options.SignatureRectangleHeight))
                .SetPageNumber(1);

                pdfSigner.SetFieldName(options.SignatureName);

                IExternalSignature privateKeySignature = new PrivateKeySignature(key, DigestAlgorithms.SHA256);

                pdfSigner.SignDetached(privateKeySignature, certificate, null, null, null, 0, PdfSigner.CryptoStandard.CMS);

                Console.WriteLine(destPdf);
            });
        }
Example #4
0
        public static void Main(String[] args)
        {
            Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
            String      alias = "";
            ICollection <X509Certificate> chain = new List <X509Certificate>();

            // searching for private key

            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }

            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
            C2_09_SignatureTypes       app        = new C2_09_SignatureTypes();

            app.Sign(SRC, String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256,
                     CryptoStandard.CMS, PdfSignatureAppearance.NOT_CERTIFIED, "Test 1", "Ghent");
            app.Sign(SRC, String.Format(DEST, 2), chain, parameters, DigestAlgorithms.SHA512,
                     CryptoStandard.CMS, PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, "Test 1", "Ghent");
            app.Sign(SRC, String.Format(DEST, 3), chain, parameters, DigestAlgorithms.SHA256,
                     CryptoStandard.CADES, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, "Test 1", "Ghent");
            app.Sign(SRC, String.Format(DEST, 4), chain, parameters, DigestAlgorithms.RIPEMD160,
                     CryptoStandard.CADES, PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED, "Test 1", "Ghent");

            app.AddWrongAnnotation(String.Format(DEST, 1), String.Format(DEST, "1_annotated_wrong"));
            app.AddAnnotation(String.Format(DEST, 1), String.Format(DEST, "1_annotated"));
            app.AddAnnotation(String.Format(DEST, 2), String.Format(DEST, "2_annotated"));
            app.AddAnnotation(String.Format(DEST, 3), String.Format(DEST, "3_annotated"));
            app.AddAnnotation(String.Format(DEST, 4), String.Format(DEST, "4_annotated"));
            app.AddText(String.Format(DEST, 1), String.Format(DEST, "1_text"));

            app.SignAgain(String.Format(DEST, 1), String.Format(DEST, "1_double"), chain, parameters, DigestAlgorithms.SHA256,
                          CryptoStandard.CMS, "Second signature test", "Ghent");
            app.SignAgain(String.Format(DEST, 2), String.Format(DEST, "2_double"), chain, parameters, DigestAlgorithms.SHA256,
                          CryptoStandard.CMS, "Second signature test", "Ghent");
            app.SignAgain(String.Format(DEST, 3), String.Format(DEST, "3_double"), chain, parameters, DigestAlgorithms.SHA256,
                          CryptoStandard.CMS, "Second signature test", "Ghent");
            app.SignAgain(String.Format(DEST, 4), String.Format(DEST, "4_double"), chain, parameters, DigestAlgorithms.SHA256,
                          CryptoStandard.CMS, "Second signature test", "Ghent");
        }
Example #5
0
        public Certificado(string caminhoPfx, string chavePfx = null)
        {
            using (var file = File.OpenRead(caminhoPfx)) {
                var password = chavePfx.ToCharArray();
                var store    = new Pkcs12Store(file, password);
                var alias    = GetCertificateAlias(store);

                Key = store.GetKey(alias).Key;

                Console.Write(Key);
                Chain = store.GetCertificateChain(alias).Select(x => x.Certificate).ToArray();
            }
        }
Example #6
0
        /// <summary>
        /// 获取证书编号
        /// </summary>
        /// <param name="path">证书路径</param>
        /// <param name="pwd">证书密码</param>
        /// <returns></returns>
        public static string GetCertId(string path, string pwd)
        {
            if (string.IsNullOrEmpty(_aliase))
            {
                GetPkcs12Store(path, pwd);
            }

            return _pkcs12Store
                .GetCertificateChain(_aliase)[0]
                .Certificate
                .SerialNumber
                .ToString();
        }
Example #7
0
        public bool Open()
        {
            if ((filename == null) || (filename.Length == 0))
            {
                this.lastError = Resources.PKCS12_FILENAME_MISSING;
                return(false);
            }

            if (!File.Exists(filename))
            {
                this.lastError = Resources.PKCS12_FILE_MISSING + filename;
                return(false);
            }

            FileStream fs = new FileStream(filename, FileMode.Open);

            store = new Pkcs12Store(fs, password.ToCharArray());

            string alias = null;

            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            fs.Close();
            key = store.GetKey(alias).Key;

            X509CertificateEntry[] x = store.GetCertificateChain(alias);
            chain = new X509Certificate[x.Length];

            for (int k = 0; k < x.Length; ++k)
            {
                chain[k] = x[k].Certificate;
            }

            if (key == null)
            {
                this.lastError = Resources.INVALID_PKCS12_CERT_PRI_KEY_MISSING;
            }
            ;
            if (chain == null || chain.Length == 0)
            {
                this.lastError = Resources.INVALID_PKCS12_CERT_PUB_KEY_MISSING;
            }

            return(key != null && chain != null && chain.Length > 0);
        }
Example #8
0
        public byte[] signPdfWithPfxFile(string pfxFile, string pinCode, string pdfFileName)
        {
            PfxSigner    signer = new PfxSigner(SignatureAlg.RSA_SHA256.getName(), pfxFile, pinCode);
            ECertificate signatureCertificate = signer.getSignersCertificate();
            Pkcs12Store  store = new Pkcs12Store(new FileStream(pfxFile, FileMode.Open), pinCode.ToCharArray());
            String       alias = "";
            string       dest  = AppDomain.CurrentDomain.BaseDirectory + "\\tmp.pdf";

            if (File.Exists(dest))
            {
                File.Delete(dest);
            }
            ICollection <Org.BouncyCastle.X509.X509Certificate> chain = new List <Org.BouncyCastle.X509.X509Certificate>();

            // searching for private key
            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }

            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

            // Creating the reader and the stamper
            PdfReader  reader  = new PdfReader(pdfFileName);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.Reason   = "";
            appearance.Location = "";
            //appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");//don't show rectangle on pdf
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CADES);
            byte[] buffer = File.ReadAllBytes(dest);
            File.Delete(dest);
            return(buffer);
        }
        public static void Main(String[] args)
        {
            DirectoryInfo directory = new DirectoryInfo(DEST);

            directory.Create();

            Properties properties = new Properties();

            // Specify the correct path to the certificate
            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read));
            String path = properties.GetProperty("PRIVATE");

            char[] pass    = properties.GetProperty("PASSWORD").ToCharArray();
            String tsaUrl  = properties.GetProperty("TSAURL");
            String tsaUser = properties.GetProperty("TSAUSERNAME");
            String tsaPass = properties.GetProperty("TSAPASSWORD");

            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            IOcspClient ocspClient = new OcspClientBouncyCastle(null);

            /* Create an instance of TSAClientBouncyCastle, an implementation of TSAClient.
             * Pass the timestamp authority server url.
             * Note that not all TSA would require user credentials.
             */
            ITSAClient tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass);

            new C3_09_SignWithTSA().Sign(SRC, DEST + RESULT_FILES[0], chain, pk,
                                         DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                                         "Test", "Ghent", null, ocspClient, tsaClient, 0);
        }
Example #10
0
        public async Task <byte[]> Sign(byte[] source, SigningProperties signingProperties)
        {
            using (var inputStream = new MemoryStream(source))
                using (var reader = new PdfReader(inputStream))
                    using (var outputStream = new MemoryStream())
                    {
                        var stampProps = new StampingProperties();
                        var signer     = new PdfSigner(reader, outputStream, stampProps);

                        signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);

                        var sap = signer.GetSignatureAppearance();

                        sap.SetLocation(signingProperties.Location);
                        sap.SetReason(signingProperties.Reason);
                        sap.SetReuseAppearance(false);

                        var certData = await s3Repository.GetDocument(signingProperties.Bucket, signingProperties.Key);

                        // code from https://stackoverflow.com/questions/12470498/how-to-read-the-pfx-file
                        using (var keyStream = new MemoryStream(certData))
                        {
                            var passphrase = signingProperties.Password;

                            if (signingProperties.KMSData != null)
                            {
                                // key is encrypted with KSM
                                var key = await kSMRepository.GetKey(signingProperties.KMSData);

                                passphrase = kSMRepository.DecryptData(passphrase, key);
                            }

                            var store = new Pkcs12Store(keyStream, signingProperties.Password.ToCharArray());

                            string alias = store.Aliases.OfType <string>().First(x => store.IsKeyEntry(x));

                            var privateKey = store.GetKey(alias).Key;

                            var keyChain = store.GetCertificateChain(alias)
                                           .Select(x => x.Certificate).ToArray();

                            IExternalSignature externalSignature = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);

                            signer.SignDetached(externalSignature, keyChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);

                            return(outputStream.ToArray());
                        }
                    }
        }
        public static void Main(String[] args)
        {
            DirectoryInfo directory = new DirectoryInfo(DEST);

            directory.Create();

            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open, FileAccess.Read), PASSWORD);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            ImageData image = ImageDataFactory.Create(IMG);

            C2_07_SignatureAppearances app = new C2_07_SignatureAppearances();
            String signatureName           = "Signature1";
            String location = "Ghent";

            app.Sign(SRC, signatureName, DEST + RESULT_FILES[0], chain, pk,
                     DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                     "Appearance 1", location, PdfSignatureAppearance.RenderingMode.DESCRIPTION, null);

            app.Sign(SRC, signatureName, DEST + RESULT_FILES[1], chain, pk,
                     DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                     "Appearance 2", location, PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION, null);

            app.Sign(SRC, signatureName, DEST + RESULT_FILES[2], chain, pk,
                     DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                     "Appearance 3", location, PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION, image);

            app.Sign(SRC, signatureName, DEST + RESULT_FILES[3], chain, pk,
                     DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                     "Appearance 4", location, PdfSignatureAppearance.RenderingMode.GRAPHIC, image);
        }
 private void RefreshStore()
 {
     _listItems.Clear();
     foreach (String alias in _store.Aliases)
     {
         KeyStoreEntryType entryType;
         if (_store.IsCertificateEntry(alias))
         {
             entryType = KeyStoreEntryType.TrustCertEntry;
         }
         else if (_store.IsKeyEntry(alias) && _store.GetCertificateChain(alias) != null &&
                  _store.GetCertificateChain(alias).Length != 0)
         {
             entryType = KeyStoreEntryType.KeyPairEntry;
         }
         else
         {
             entryType = KeyStoreEntryType.KeyEntry;
         }
         X509Certificate cert = _store.GetCertificate(alias).Certificate;
         _listItems.Add(new ListItemEntry(entryType, alias, cert,
                                          Repository.Instance.IsRevokedCertificate(cert.SerialNumber.ToString())));
     }
 }
Example #13
0
        public static void Main(String[] args)
        {
            DirectoryInfo directory = new DirectoryInfo(DEST);

            directory.Create();

            Properties properties = new Properties();

            // Specify the correct path to the certificate
            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read));
            String path = properties.GetProperty("PRIVATE");

            char[] pass = properties.GetProperty("PASSWORD").ToCharArray();

            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            /* Create a CrlClientOnline instance with specified Certificate Revocation List's URL.
             * The exact URL for the CRL access point is specific for every CA provider.
             * This one is specific for CAcert certificates.
             */
            ICrlClient         crlClient = new CrlClientOnline("https://crl.cacert.org/revoke.crl");
            IList <ICrlClient> crlList   = new List <ICrlClient>();

            crlList.Add(crlClient);

            new C3_04_SignWithCRLOnline().Sign(SRC, DEST + RESULT_FILES[0], chain, pk,
                                               DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                                               "Test", "Ghent", crlList, null, null, 0);
        }
Example #14
0
        private void processCert()
        {
            string      alias = null;
            Pkcs12Store pk12;

            //First we'll read the certificate file
            Stream fs;

            if (this.path != null)
            {
                fs = new FileStream(this.Path, FileMode.Open, FileAccess.Read);
            }
            else
            {
                fs = new MemoryStream(this.rawData);
            }
            pk12 = new Pkcs12Store(fs, this.password.ToCharArray());

            //then Iterate throught certificate entries to find the private key entry
            foreach (string al in pk12.Aliases)
            {
                if (pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            //IEnumerator i = pk12.Aliases.GetEnumerator();
            //while (i.MoveNext())
            //{
            //    alias = ((string)i.Current);
            //    if (pk12.IsKeyEntry(alias))
            //        break;
            //}
            fs.Close();

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

            //this.tsc = new TSAClientBouncyCastle("http://www.ca-soft.com/request.aspx", TSA_ACCNT, TSA_PASSW);
            //this.tsc = new TSAClientBouncyCastle("http://www.ca-soft.com/request.aspx");
        }
Example #15
0
        virtual public void XmlDSigRsaKS()
        {
            Directory.CreateDirectory(DestDir);

            String filename = "xfa.signed.pdf";
            String output   = DestDir + filename;

            MemoryStream ks = new MemoryStream();

            using (FileStream reader = new FileStream(KEYSTORE, FileMode.Open)) {
                byte[] buffer = new byte[reader.Length];
                reader.Read(buffer, 0, (int)reader.Length);
                ks.Write(buffer, 0, buffer.Length);
                ks.Position = 0;
            }
            Pkcs12Store            store = new Pkcs12Store(ks, PASSWORD.ToCharArray());
            String                 alias = "";
            List <X509Certificate> chain = new List <X509Certificate>();

            // searching for private key

            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }

            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

            SignWithCertificate(Src, output, parameters, chain.ToArray(), DigestAlgorithms.SHA1);

            String cmp = SaveXmlFromResult(output);

            Assert.IsTrue(VerifySignature(cmp), "XmlDSig Verification");

            Assert.IsTrue(CompareXmls(cmp, CmpDir + filename.Replace(".pdf", ".xml")));
        }
Example #16
0
        public void SignDocument(SigningDocument signingDocument)
        {
            string KEYSTORE = $"{signingDocument.CertificatDestination}";

            char[] PASSWORD = $"{signingDocument.Password}".ToCharArray();

            Pkcs12Store pk12 = new Pkcs12Store(new FileStream(KEYSTORE,
                                                              FileMode.Open, FileAccess.Read), PASSWORD);
            string alias = null;

            foreach (object a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

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

            var    f    = signingDocument.File.OpenReadStream();
            string DEST = $"{signingDocument.destinationSave}\\Signed{signingDocument.File.FileName}";

            PdfReader p      = new PdfReader(f);
            PdfSigner signer = new PdfSigner(p, new FileStream(DEST, FileMode.Create),
                                             new StampingProperties());

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetLocation(signingDocument.Location)
            .SetPageRect(new Rectangle(425, 0, 150, 75))
            .SetPageNumber(1);
            signer.SetFieldName("MyFieldName");

            IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256);

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
        }
Example #17
0
        void LoadPkcs12(Stream stream, string password)
        {
            var  pkcs12        = new Pkcs12Store(stream, password.ToCharArray());
            bool hasPrivateKey = false;

            foreach (string alias in pkcs12.Aliases)
            {
                if (!pkcs12.IsKeyEntry(alias))
                {
                    continue;
                }

                var chain = pkcs12.GetCertificateChain(alias);
                var key   = pkcs12.GetKey(alias);

                if (!key.Key.IsPrivate)
                {
                    continue;
                }

                hasPrivateKey = true;

                if (chain.Length == 0 || !CanSign(chain[0].Certificate))
                {
                    continue;
                }

                CertificateChain = new X509CertificateChain();
                Certificate      = chain[0].Certificate;
                PrivateKey       = key.Key;

                foreach (var entry in chain)
                {
                    CertificateChain.Add(entry.Certificate);
                }

                return;
            }

            if (!hasPrivateKey)
            {
                throw new ArgumentException("The stream did not contain a private key.", nameof(stream));
            }

            throw new ArgumentException("The stream did not contain a certificate that could be used to create digital signatures.", nameof(stream));
        }
Example #18
0
        public static void Main(String[] args)
        {
            DirectoryInfo directory = new DirectoryInfo(DEST);

            directory.Create();

            Properties properties = new Properties();

            /* This properties file should contain a CAcert certificate that belongs to the user,
             * according to the original sample purpose. However right now it contains a simple
             * self-signed certificate in p12 format, which serves as a stub.
             */
            properties.Load(new FileStream("../../../resources/encryption/signkey.properties",
                                           FileMode.Open, FileAccess.Read));

            // Get path to the p12 file
            String path = properties.GetProperty("PRIVATE");

            // Get a password
            char[] pass = properties.GetProperty("PASSWORD").ToCharArray();

            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            new C3_01_SignWithCAcert().Sign(SRC, DEST + RESULT_FILES[0], chain, pk,
                                            DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                                            "Test", "Ghent", null, null, null, 0);
        }
        public static void Main(String[] args)
        {
            DirectoryInfo directory = new DirectoryInfo(DEST);

            directory.Create();

            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open, FileAccess.Read), PASSWORD);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            C2_06_SignatureAppearance app = new C2_06_SignatureAppearance();

            app.Sign1(SRC, "Signature1", DEST + RESULT_FILES[0], chain, pk,
                      DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                      "Custom appearance example", "Ghent");

            app.Sign2(SRC, "Signature1", DEST + RESULT_FILES[1], chain, pk,
                      DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                      "Custom appearance example", "Ghent");

            app.Sign3(SRC, "Signature1", DEST + RESULT_FILES[2], chain, pk,
                      DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                      "Custom appearance example", "Ghent");

            app.Sign4(SRC, "Signature1", DEST + RESULT_FILES[3], chain, pk,
                      DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                      "Custom appearance example", "Ghent");
        }
Example #20
0
        public static void Main(String[] args)
        {
            DirectoryInfo directory = new DirectoryInfo(DEST);

            directory.Create();

            Properties properties = new Properties();

            // Specify the correct path to the certificate
            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read));
            String path = properties.GetProperty("PRIVATE");

            char[] pass = properties.GetProperty("PASSWORD").ToCharArray();

            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            /* Create an instance of OcspClientBouncyCastle, an implementation of OcspClient.
             * In the current sample it is not needed to verify the OCSP response,
             * that is why null is passed as verifier parameter.
             */
            IOcspClient ocspClient = new OcspClientBouncyCastle(null);

            new C3_07_SignWithOCSP().Sign(SRC, DEST + RESULT_FILES[0], chain, pk,
                                          DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                                          "Test", "Ghent", null, ocspClient, null, 0);
        }
Example #21
0
        void LoadPkcs12(Stream stream, string password)
        {
            var pkcs12 = new Pkcs12Store(stream, password.ToCharArray());

            foreach (string alias in pkcs12.Aliases)
            {
                if (!pkcs12.IsKeyEntry(alias))
                {
                    continue;
                }

                var chain = pkcs12.GetCertificateChain(alias);
                var key   = pkcs12.GetKey(alias);

                if (!key.Key.IsPrivate || chain.Length == 0)
                {
                    continue;
                }

                var flags = chain[0].Certificate.GetKeyUsageFlags();

                if (flags != X509KeyUsageFlags.None && (flags & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
                {
                    continue;
                }

                CheckCertificateCanBeUsedForSigning(chain[0].Certificate);

                CertificateChain = new X509CertificateChain();
                Certificate      = chain[0].Certificate;
                PrivateKey       = key.Key;

                foreach (var entry in chain)
                {
                    CertificateChain.Add(entry.Certificate);
                }

                break;
            }

            if (PrivateKey == null)
            {
                throw new ArgumentException("The stream did not contain a private key.", "stream");
            }
        }
Example #22
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(Stream stream, string password)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

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

            var pkcs12 = new Pkcs12Store(stream, password.ToCharArray());

            foreach (string alias in pkcs12.Aliases)
            {
                if (pkcs12.IsKeyEntry(alias))
                {
                    var chain = pkcs12.GetCertificateChain(alias);
                    var 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))
                {
                    var entry = pkcs12.GetCertificate(alias);

                    if (unique.Add(entry.Certificate))
                    {
                        certs.Add(entry.Certificate);
                    }
                }
            }
        }
Example #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="certPwd"></param>
        /// <returns></returns>
        public static UnionPayCertificate GetSignCertificate(string certificate, string certPwd)
        {
            FileStream fs          = null;
            var        Certificate = new UnionPayCertificate();

            try
            {
                fs = new FileStream(certificate, FileMode.Open, FileAccess.Read);
                var store = new Pkcs12Store(fs, certPwd.ToCharArray());

                var alias = string.Empty;
                foreach (string n in store.Aliases)
                {
                    if (store.IsKeyEntry(n))
                    {
                        alias = n;
                    }
                }

                var chain = store.GetCertificateChain(alias);
                var cert  = chain[0].Certificate;

                Certificate.key    = store.GetKey(alias).Key;
                Certificate.cert   = cert;
                Certificate.certId = cert.SerialNumber.ToString();
                //return new UnionPayCertificate
                //{
                //    key = store.GetKey(alias).Key,
                //    cert = cert,
                //    certId = cert.SerialNumber.ToString()
                //};
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
            return(Certificate);
        }
        /// <summary>
        /// Electronically signs the PDF of agreement report.
        /// </summary>
        /// <param name="id">Employee's ID.</param>
        /// <param name="pfxPath">Path of PFX file.</param>
        /// <param name="password">Password to open PFX.</param>
        public static void SignPDF(int id, string pfxPath, char[] password)
        {
            ICipherParameters privateKey;

            X509Certificate[] chain;
            using (var fileStream = new FileStream(pfxPath, FileMode.Open, FileAccess.Read)) {
                var    pk12  = new Pkcs12Store(fileStream, password);
                string alias = null;
                foreach (object a in pk12.Aliases)
                {
                    alias = a as string;
                    if (pk12.IsKeyEntry(alias))
                    {
                        break;
                    }
                }
                privateKey = pk12.GetKey(alias).Key;

                var certificate = pk12.GetCertificateChain(alias);
                chain = new X509Certificate[certificate.Length];
                for (int k = 0; k < certificate.Length; ++k)
                {
                    chain[k] = certificate[k].Certificate;
                }
            }

            using (var reader = new PdfReader(ReportGenerator.GetReportPath(id)))
                using (var fileStream = new FileStream(ReportGenerator.GetReportPath(id, "_SIGNED"), FileMode.Create)) {
                    var signer = new PdfSigner(reader, fileStream, new StampingProperties());
                    int lastPage;
                    using (var r = new PdfReader(ReportGenerator.GetReportPath(id)))
                        using (var document = new PdfDocument(r)) {
                            lastPage = document.GetNumberOfPages();
                        }
                    var appearance = signer.GetSignatureAppearance()
                                     .SetReason("Me comprometo al uso responsable del software especificado en este documento.")
                                     .SetPageRect(new Rectangle(100, 1000, 200, 100))
                                     .SetPageNumber(lastPage);
                    signer.SetFieldName("MyFieldName");

                    var pks = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);
                    signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
                }
        }
        public static void Main(String[] args)
        {
            DirectoryInfo directory = new DirectoryInfo(DEST);

            directory.Create();

            Properties properties = new Properties();

            // Specify the correct path to the certificate
            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read));
            String path = properties.GetProperty("PRIVATE");

            char[] pass = properties.GetProperty("PASSWORD").ToCharArray();

            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass);
            string      alias = null;

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            ICipherParameters pk = pk12.GetKey(alias).Key;

            X509CertificateEntry[] ce    = pk12.GetCertificateChain(alias);
            X509Certificate[]      chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
            {
                chain[k] = ce[k].Certificate;
            }

            IList <ICrlClient> crlList = new List <ICrlClient>();

            // Add the default implementation of the CrlClientOnline
            crlList.Add(new CrlClientOnline());

            new C3_03_SignWithCRLDefaultImp().Sign(SRC, DEST + RESULT_FILES[0], chain, pk,
                                                   DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS,
                                                   "Test", "Ghent", crlList, null, null, 0);
        }
Example #26
0
        /// <summary>
        /// 初始化签名证书
        /// </summary>
        /// <param name="certPath">证书路径</param>
        /// <param name="certPwd">密码</param>
        private static void InitSignCert(string certPath, string certPwd)
        {
            Log.Info("读取签名证书……,地址:" + certPath);

            FileStream fileStream = null;

            try
            {
                if (File.Exists(certPath))
                {
                    Cert signCert = new Cert();
                    using (fileStream = new FileStream(certPath, FileMode.Open))
                    {
                        Pkcs12Store store = new Pkcs12Store(fileStream, certPwd.ToCharArray());

                        string pName = null;
                        foreach (string n in store.Aliases)
                        {
                            if (store.IsKeyEntry(n))
                            {
                                pName = n;
                                //break;
                            }
                        }

                        signCert.AsymmetricKey = store.GetKey(pName).Key;
                        X509CertificateEntry[] chain = store.GetCertificateChain(pName);
                        signCert.X509Certificate = chain[0].Certificate;
                        signCert.CertId          = signCert.X509Certificate.SerialNumber.ToString();

                        SignCerts[certPath] = signCert;
                    }

                    Log.Info("签名证书读取成功,序列号:" + signCert.CertId);
                }
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
Example #27
0
        private static void initSignCert(string certPath, string certPwd)
        {
            log.Info("读取签名证书:" + certPath);

            FileStream fileStream = null;

            try
            {
                fileStream = new FileStream(certPath, FileMode.Open, FileAccess.Read);

                Pkcs12Store store = new Pkcs12Store(fileStream, certPwd.ToCharArray());

                string pName = null;
                foreach (string n in store.Aliases)
                {
                    if (store.IsKeyEntry(n))
                    {
                        pName = n;
                        //break;
                    }
                }

                Cert signCert = new Cert();
                signCert.key = store.GetKey(pName).Key;
                X509CertificateEntry[] chain = store.GetCertificateChain(pName);
                signCert.cert   = chain[0].Certificate;
                signCert.certId = signCert.cert.SerialNumber.ToString();

                signCerts[certPath] = signCert;
                log.Info("签名证书读取成功,序列号:" + signCert.certId);
            }
            catch (Exception e)
            {
                log.Error("签名证书读取失败,异常:" + e);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
Example #28
0
        public void XadesBesRsaPackage()
        {
            Directory.CreateDirectory(DestDir);

            String filename = "xfa.signed.bes.package.pdf";
            String output   = DestDir + filename;

            MemoryStream ks = new MemoryStream();

            using (FileStream reader = new FileStream(KEYSTORE, FileMode.Open)) {
                byte[] buffer = new byte[reader.Length];
                reader.Read(buffer, 0, (int)reader.Length);
                ks.Write(buffer, 0, buffer.Length);
                ks.Position = 0;
            }
            Pkcs12Store            store = new Pkcs12Store(ks, PASSWORD.ToCharArray());
            String                 alias = "";
            List <X509Certificate> chain = new List <X509Certificate>();

            // searching for private key

            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }

            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

            SignBesPackage(Src, output, XfaXpathConstructor.XdpPackage.Template, parameters, chain.ToArray(), DigestAlgorithms.SHA1);

            String cmp = SaveXmlFromResult(output);
        }
Example #29
0
        static void LoadPkcs12(string path, string password, out List <X509Certificate> certificates, out AsymmetricKeyParameter privateKey)
        {
            certificates = null;
            privateKey   = null;

            using (var stream = File.OpenRead(path)) {
                var pkcs12 = new Pkcs12Store(stream, password.ToCharArray());

                foreach (string alias in pkcs12.Aliases)
                {
                    if (!pkcs12.IsKeyEntry(alias))
                    {
                        continue;
                    }

                    var chain = pkcs12.GetCertificateChain(alias);
                    var key   = pkcs12.GetKey(alias);

                    if (!key.Key.IsPrivate || chain.Length == 0)
                    {
                        continue;
                    }

                    var flags = chain[0].Certificate.GetKeyUsageFlags();

                    if (flags != X509KeyUsageFlags.None && (flags & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
                    {
                        continue;
                    }

                    certificates = new List <X509Certificate> ();
                    certificates.Add(chain[0].Certificate);
                    privateKey = key.Key;

                    foreach (var entry in chain)
                    {
                        certificates.Add(entry.Certificate);
                    }

                    return;
                }
            }
        }
Example #30
0
        public static void Main(String[] args)
        {
            Properties properties = new Properties();

            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open));
            String path = properties["PRIVATE"];

            char[] pass    = properties["PASSWORD"].ToCharArray();
            String tsaUrl  = properties["TSAURL"];
            String tsaUser = properties["TSAUSERNAME"];
            String tsaPass = properties["TSAPASSWORD"];

            Pkcs12Store ks = new Pkcs12Store();

            ks.Load(new FileStream(path, FileMode.Open), pass);
            String alias = "";

            foreach (string al in ks.Aliases)
            {
                if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyParameter  pk    = ks.GetKey(alias).Key;
            IList <X509Certificate> chain = new List <X509Certificate>();

            foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias))
            {
                chain.Add(entry.Certificate);
            }
            IOcspClient           ocspClient = new OcspClientBouncyCastle();
            TSAClientBouncyCastle tsaClient  = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass);

            tsaClient.SetTSAInfo(new TSAInfoTimeStampLogger());
            C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test",
                                      "Ghent",
                                      null, ocspClient, tsaClient, 0);
            Console.ReadKey();
        }