Ejemplo n.º 1
0
        public static void Main(String[] args)
        {
            string[] dirs = Directory.GetFiles(@"c:\PATHTODOCS", "*");

            Org.BouncyCastle.Pkcs.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_01_SignHelloWorld       app        = new C2_01_SignHelloWorld();

            foreach (string dir in dirs)
            {
                app.Sign(dir, String.Format(dir + ".pdf", 1), chain, parameters, DigestAlgorithms.SHA256,
                         CryptoStandard.CMS, "Food Safety", "Prime Time International");
            }
        }
Ejemplo n.º 2
0
        public void Sign(String keystore, String src, String name, String dest)
        {
            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;

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

            appearance.SetVisibleSignature(name);
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(parameters, "SHA-256");

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
        }
Ejemplo n.º 3
0
        public void setKeyStore(Pkcs12Store keystore, string hashAlgorithm) //Getkey
        {
            //get name
            String alias = "";

            foreach (string al in keystore.Aliases)
            {
                if (keystore.IsKeyEntry(al) && keystore.GetKey(al).Key.IsPrivate) // ****  what this if do ?
                {
                    alias = al;
                    break;
                }
            }

            //get privatekey
            this.privateKey = keystore.GetKey(alias).Key;

            //create instance of Cretificate list for Long Time
            this.chain = new List <Org.BouncyCastle.X509.X509Certificate>();
            foreach (X509CertificateEntry entry in keystore.GetCertificateChain(alias))
            {
                this.chain.Add(entry.Certificate);
            }

            this.signature = new PrivateKeySignature(privateKey, hashAlgorithm);
        }
Ejemplo n.º 4
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();

            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;
            ICollection <X509Certificate> chain = new List <X509Certificate>();

            foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias))
            {
                chain.Add(entry.Certificate);
            }
            IOcspClient ocspClient = new OcspClientBouncyCastle();

            C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent",
                                      null, ocspClient, null, 0);
        }
Ejemplo n.º 5
0
        public byte[] SignHash(string hexhash, string password)
        {
            byte[]      hash  = StringToByteArray(hexhash);
            Pkcs12Store store = new Pkcs12Store(getCertificate(), password.ToCharArray());
            String      alias = "";

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

            X509CertificateEntry[] chain = store.GetCertificateChain(alias);
            List <Org.BouncyCastle.X509.X509Certificate> c = new List <Org.BouncyCastle.X509.X509Certificate>();

            foreach (X509CertificateEntry en in chain)
            {
                c.Add(en.Certificate);
            }
            PrivateKeySignature signature = new PrivateKeySignature(pk.Key, "SHA256");
            String   hashAlgorithm        = signature.GetHashAlgorithm();
            PdfPKCS7 sgn         = new PdfPKCS7(null, c, hashAlgorithm, false);
            DateTime signingTime = DateTime.Now;

            byte[] sh           = sgn.getAuthenticatedAttributeBytes(hash, null, null, CryptoStandard.CMS);
            byte[] extSignature = signature.Sign(sh);
            sgn.SetExternalDigest(extSignature, null, signature.GetEncryptionAlgorithm());
            return(sgn.GetEncodedPKCS7(hash, null, null, null, CryptoStandard.CMS));
        }
Ejemplo n.º 6
0
        public void ConvertPfxToPem(
            string pfxPath,
            string pfxPassword,
            string keyPath)
        {
            using (Stream stream = File.Open(pfxPath, FileMode.Open))
            {
                Pkcs12Store pkcs = new Pkcs12Store(stream, pfxPassword.ToCharArray());

                foreach (string alias in pkcs.Aliases)
                {
                    if (pkcs.IsKeyEntry(alias) && pkcs.GetKey(alias).Key.IsPrivate)
                    {
                        AsymmetricKeyParameter privateKey = pkcs.GetKey(alias).Key;

                        using (Stream s = new FileStream(keyPath, FileMode.Create))
                            using (TextWriter textWriter = new StreamWriter(s))
                            {
                                var generator = new MiscPemGenerator(privateKey);

                                PemWriter pemWriter = new PemWriter(textWriter);
                                pemWriter.WriteObject(generator);
                                textWriter.Flush();
                            }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        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_05_CustomAppearance     app        = new C2_05_CustomAppearance();

            app.Sign(SRC, "Signature1", DEST, chain, parameters, DigestAlgorithms.SHA256,
                     CryptoStandard.CMS, "Custom appearance example", "Ghent");
        }
Ejemplo n.º 8
0
        public static void Main(String[] args)
        {
            Directory.CreateDirectory(OUT_DIR);

            // we load our private key from the key store
            Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
            String      alias = "";

            // searching for private key
            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            IList <X509Certificate> chain = new List <X509Certificate>();

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


            C4_09_DeferredSigning app = new C4_09_DeferredSigning();

            app.EmptySignature(SRC, TEMP, "sig", chain);
            app.CreateSignature(TEMP, DEST, "sig", pk, chain);
        }
Ejemplo n.º 9
0
        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_08_SignatureMetadata    app        = new C2_08_SignatureMetadata();

            app.Sign(SRC, "Signature1", String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256,
                     CryptoStandard.CMS, "Appearance 1", "Ghent", "555 123 456", new DateTime(2012, 8, 5), "Bruno L. Specimen");
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            C2_04_CreateEmptyField appCreate = new C2_04_CreateEmptyField();

            appCreate.CreatePdf(UNSIGNED);
            appCreate.AddField(SRC, UNSIGNED2);

            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_03_SignEmptyField       appSign    = new C2_03_SignEmptyField();

            appSign.Sign(UNSIGNED, SIGNAME, DEST, chain, parameters, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent");
        }
Ejemplo n.º 11
0
        private void ExportKey(ListItemEntry entry, String algorithm, char[] password, String path)
        {
            AsymmetricKeyEntry keyentry = _store.GetKey(entry.Alias);
            string             pem      = PemUtilities.Encode(keyentry.Key, algorithm, password,
                                                              Repository.Srand);

            File.WriteAllText(path, pem);
        }
Ejemplo n.º 12
0
        public async Task DigitallySign(int idDocument, string userId, string password, byte[] certificateData, string reason, string location)
        {
            var document = await dbContext
                           .Documents
                           .FirstAsync(it => it.IdDocument == idDocument);

            var lastState = await dbContext.DocumentStates.Include(it => it.DocumentData).Where(it => it.IdDocument == idDocument).LastAsync();

            var unsignedData = ((DocumentDataUpload)lastState.DocumentData).Data;

            var store = new Pkcs12Store(new MemoryStream(certificateData), password.ToCharArray());
            var alias = string.Empty;

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

            var pk    = store.GetKey(alias);
            var chain = new List <X509Certificate>();

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

            var certificate = new System.Security.Cryptography.X509Certificates.X509Certificate(certificateData, password);

            var signedPdfData = new MemoryStream();

            using (var reader = new PdfReader(unsignedData))
            {
                var stp = PdfStamper.CreateSignature(reader, signedPdfData, '\0');
                stp.SignatureAppearance.Reason   = reason;
                stp.SignatureAppearance.Location = location;
                stp.SignatureAppearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, null);
                var es = new PrivateKeySignature(pk.Key as RsaPrivateCrtKeyParameters, DigestAlgorithms.SHA256);
                MakeSignature.SignDetached(stp.SignatureAppearance, es, chain, null, null, null, 0, CryptoStandard.CMS);

                stp.Close();
            }

            dbContext.Entry(lastState).State = EntityState.Detached;
            lastState.IdDocumentState        = 0;
            lastState.IdDocumentData         = 0;
            lastState.StatusDate             = DateTime.Now;
            lastState.IsDigitallySigned      = true;
            lastState.Version      = GetNextVersion(lastState.Version, lastState.DocumentStatus);
            lastState.DocumentData = new DocumentDataUpload {
                Data = signedPdfData.ToArray()
            };

            dbContext.DocumentStates.Add(lastState);
        }
        public static string GetPayloadSignature(string payload)
        {
            string keypairPath     = ConfigurationManager.AppSettings["keypairPath"];
            string keypairPassword = ConfigurationManager.AppSettings["keypairPassword"];

            FileStream  fileStream   = null;
            Pkcs12Store keypairStore = null;

            try
            {
                fileStream   = new FileStream(keypairPath, FileMode.Open, FileAccess.Read);
                keypairStore = new Pkcs12Store(fileStream, keypairPassword.ToCharArray());
            }
            catch (FileNotFoundException e)
            {
                throw new ApiException(400, "\n\nContenedor no encontrado, verifique la ruta.\n\n" + e.Message);
            }
            catch (Exception e)
            {
                throw new ApiException(400, "\n\nPassword del contenedor erróneo.\n\n" + e.Message);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }

            string alias = null;

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

            AsymmetricKeyEntry     pKey       = keypairStore.GetKey(alias);
            ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters)pKey.Key;

            byte[] tmpPayload = Encoding.UTF8.GetBytes(payload);

            ISigner sign = SignerUtilities.GetSigner("SHA-256withECDSA");

            sign.Init(true, privateKey);
            sign.BlockUpdate(tmpPayload, 0, tmpPayload.Length);

            byte[] signature = sign.GenerateSignature();

            byte[] asciiBytes = Hex.Encode(signature);
            char[] asciiChars = new char[Encoding.UTF8.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
            Encoding.UTF8.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
            string xSignature = new string(asciiChars);

            return(xSignature);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Sign (fill) named field in the document soft way (using existing stamper)
        /// </summary>
        /// <param name="stamper">PdfStamper</param>
        /// <param name="fieldName">Field to be signed</param>
        /// <param name="reason">Sign reason</param>
        /// <param name="location">Sign location</param>
        /// <param name="graphics">Sign graphic</param>
        /// <param name="certFile">PFX certificate</param>
        /// <param name="certPassword">password of certificate</param>
        /// <param name="renderingMode">SignatureRender renderingMode</param>
        /// <param name="certificationLevel">PdfSignatureAppearance Certification Level</param>
        /// <returns>Successfull or not</returns>
        public static bool SignField(ref PdfStamper stamper,
                                     string fieldName,
                                     string reason,
                                     string location,
                                     Bitmap graphics,
                                     string certFile,
                                     string certPassword,
                                     PdfSignatureAppearance.SignatureRender renderingMode = PdfSignatureAppearance.SignatureRender.GraphicAndDescription,
                                     int certificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED)
        {
            bool result = false;

            try
            {
                if (stamper.Reader.AcroFields.Fields.ContainsKey(fieldName))
                {
                    PdfSignatureAppearance psa = GetPSA(fieldName, stamper, graphics, reason, location, renderingMode, certificationLevel);

                    Pkcs12Store store = new Pkcs12Store(new FileStream(certFile, FileMode.Open), certPassword.ToCharArray());
                    string      alias = "";
                    ICollection <X509Certificate> chain = new List <X509Certificate>();

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

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

                    RsaPrivateCrtKeyParameters parameters = ake.Key as RsaPrivateCrtKeyParameters;

                    psa.SetCrypto(parameters, chain.ToArray(), null, PdfSignatureAppearance.WINCER_SIGNED);

                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = false;
            }

            return(result);
        }
Ejemplo n.º 15
0
        public static void Main(String[] args)
        {
            LoggerFactory.GetInstance().SetLogger(new SysoLogger());
            Properties properties = new Properties();

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

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

            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);
            }
            FileStream   ins  = new FileStream(CRLURL, FileMode.Open);
            MemoryStream baos = new MemoryStream();

            byte[] buf = new byte[1024];
            int    readedBytes;

            while ((readedBytes = ins.Read(buf, 0, 1024)) > 0)
            {
                baos.Write(buf, 0, readedBytes);
            }
            ins.Close();
            ICrlClient crlClient = new CrlClientOffline(baos.ToArray());

            X509CrlParser crlParser = new X509CrlParser();
            X509Crl       crl       = crlParser.ReadCrl(new FileStream(CRLURL, FileMode.Open));

            Console.WriteLine("CRL valid until: " + crl.NextUpdate);
            Console.WriteLine("Certificate revoked: " + crl.IsRevoked(chain[0]));

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

            crlList.Add(crlClient);
            C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test",
                                      "Ghent",
                                      crlList, null, null, 0);
        }
Ejemplo n.º 16
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);

            C3_12_SignWithEstimatedSize app = new C3_12_SignWithEstimatedSize();
            bool succeeded     = false;
            int  estimatedSize = 10300;

            while (!succeeded)
            {
                try {
                    Console.WriteLine("Attempt: " + estimatedSize + " bytes");
                    C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent",
                                              null, ocspClient, tsaClient, estimatedSize);
                    succeeded = true;
                    Console.WriteLine("Succeeded!");
                }
                catch (IOException ioe) {
                    Console.WriteLine("Not succeeded: " + ioe.Message);
                    estimatedSize += 50;
                }
            }
            Console.ReadKey();
        }
Ejemplo n.º 17
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");
        }
Ejemplo n.º 18
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);
        }
Ejemplo n.º 19
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);
        }
Ejemplo n.º 20
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");
        }
Ejemplo n.º 21
0
        public void EncryptWithCertificateAndSignTest()
        {
            String inPdf  = SOURCE_FOLDER + "in.pdf";
            String outPdf = DEST_FOLDER + "encrypt_cert_signed.pdf";
            String tmpPdf = DEST_FOLDER + "encrypt_cert.pdf";

            EncryptPdfWithCertificate(inPdf, tmpPdf, SOURCE_FOLDER + "test.cer");

            X509Certificate cert = new X509Certificate();

            cert.Import(SOURCE_FOLDER + "test.cer");

            Pkcs12Store pkstore = new Pkcs12Store(new FileStream(SOURCE_FOLDER + "test.p12", FileMode.Open, FileAccess.Read), "kspass".ToCharArray());
            string      pkalias = null;

            foreach (object a in pkstore.Aliases)
            {
                pkalias = ((string)a);
                if (pkstore.IsKeyEntry(pkalias))
                {
                    break;
                }
            }
            ICipherParameters certpk = pkstore.GetKey(pkalias).Key;

            X509Certificate2 signCert = new X509Certificate2(SOURCE_FOLDER + "test.p12", "kspass");

            CertSign(signCert, new X509CertificateParser(), outPdf, new PdfReader(tmpPdf, Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert), certpk), "reason", "location");
        }
Ejemplo n.º 22
0
    private void processCert()
    {
        string      alias = null;
        Pkcs12Store pk12;

        //First we'll read the certificate file
        pk12 = new Pkcs12Store(new FileStream(this.Path, FileMode.Open, FileAccess.Read), this.password.ToCharArray());

        //then Iterate throught certificate entries to find the private key entry

        IEnumerator i = pk12.Aliases.GetEnumerator();

        while (i.MoveNext())
        {
            alias = ((string)i.Current);
            if (pk12.IsKeyEntry(alias))
            {
                break;
            }
        }

        akp = pk12.GetKey(alias).Key;
        X509CertificateEntry[] ce = pk12.GetCertificateChain(alias);
        this.chain = new X509Certificate[ce.Length];
        for (int k = 0; k < ce.Length; ++k)
        {
            chain[k] = ce[k].Certificate;
        }
    }
Ejemplo n.º 23
0
        public void testSignSimpleECDsa()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";
            string storePath    = @"..\..\..\..\simple\keystore\test1234.p12";

            char[] storePass  = "******".ToCharArray();
            string storeAlias = "ECDSAkey";

            Pkcs12Store            pkcs12 = new Pkcs12Store(new FileStream(storePath, FileMode.Open, FileAccess.Read), storePass);
            AsymmetricKeyParameter key    = pkcs12.GetKey(storeAlias).Key;

            X509CertificateEntry[] chainEntries = pkcs12.GetCertificateChain(storeAlias);
            X509Certificate[]      chain        = new X509Certificate[chainEntries.Length];
            for (int i = 0; i < chainEntries.Length; i++)
            {
                chain[i] = chainEntries[i].Certificate;
            }
            PrivateKeySignature signature = new PrivateKeySignature(key, "SHA512");

            using (PdfReader pdfReader = new PdfReader(testFileName))
                using (FileStream result = File.Create("circles-ECDSA-BC-signed-simple.pdf"))
                {
                    PdfSigner  pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode());
                    ITSAClient tsaClient = null;

                    pdfSigner.SignDetached(signature, chain, null, null, tsaClient, 0, PdfSigner.CryptoStandard.CMS);
                }
        }
Ejemplo n.º 24
0
        public void testSignSimpleDsaSha256()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";
            string storePath    = @"..\..\..\..\simple\keystore\test1234.p12";

            char[] storePass  = "******".ToCharArray();
            string storeAlias = "DSAkey";

            Pkcs12Store            pkcs12 = new Pkcs12Store(new FileStream(storePath, FileMode.Open, FileAccess.Read), storePass);
            AsymmetricKeyParameter key    = pkcs12.GetKey(storeAlias).Key;

            X509CertificateEntry[] chainEntries = pkcs12.GetCertificateChain(storeAlias);
            X509Certificate[]      chain        = new X509Certificate[chainEntries.Length];
            for (int i = 0; i < chainEntries.Length; i++)
            {
                chain[i] = chainEntries[i].Certificate;
            }
            PrivateKeySignatureContainer signature = new PrivateKeySignatureContainer(key, chain, "SHA256withDSA");

            using (PdfReader pdfReader = new PdfReader(testFileName))
                using (FileStream result = File.Create("circles-DSASHA256-BC-signed-simple.pdf"))
                {
                    PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode());

                    pdfSigner.SignExternalContainer(signature, 8192);
                }
        }
        public static UnionPayCertificate GetSignCertificate(string certificate, string certPwd)
        {
            var stream = File.Exists(certificate) ? File.OpenRead(certificate) : (Stream) new MemoryStream(Convert.FromBase64String(certificate));
            var store  = new Pkcs12Store(stream, 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;

            return(new UnionPayCertificate
            {
                key = store.GetKey(alias).Key,
                cert = cert,
                certId = cert.SerialNumber.ToString()
            });
        }
        static void Main(string[] args)
        {
            var certificateData = File.ReadAllBytes("YOUR_p7b_FILE");
            var cert            = new X509CertificateParser().ReadCertificate(certificateData);
            //I just wanted to know if I can see the publicKey somehow
            //var publicKey = cert.GetPublicKey();

            var store      = new Pkcs12Store(File.OpenRead("YOUR_p12_File"), "test".ToCharArray());
            var privateKey = store.GetKey("THE_NAME_OF_KEY_YOU_WANT_TO_GET").Key;

            var signedDataGen = new CmsSignedDataGenerator();

            signedDataGen.AddSigner(privateKey, cert, CmsSignedDataGenerator.EncryptionRsa, CmsSignedDataGenerator.DigestSha512);

            var zipContent = new CmsProcessableFile(new FileInfo("YOUR_DATA_FILE"));
            //For me a zip
            var signedData = signedDataGen.Generate(zipContent, true);

            var envDataGen = new CmsEnvelopedDataGenerator();

            envDataGen.AddKeyTransRecipient(cert);

            var sData     = new CmsProcessableByteArray(signedData.GetEncoded());
            var enveloped = envDataGen.Generate(sData, CmsEnvelopedDataGenerator.DesEde3Cbc);

            var dos          = new DerOutputStream(File.OpenWrite("YOUR_DATA_FILE.zip.encrypted.sig)"));
            var bytesToWrite = enveloped.GetEncoded();

            dos.Write(bytesToWrite, 0, bytesToWrite.Length);
            dos.Flush();
            dos.Close();
        }
        /// <summary>
        /// Load the Root Certificate byte array to digitally sign other certificates.
        /// </summary>
        /// <param name="RootPFXCertificate">The byte array that contains the Root PFX file.</param>
        /// <param name="PFXFilePassword">The PFX password of the Root Certificate.</param>
        public void LoadRootCertificate(byte[] RootPFXCertificate, string PFXFilePassword)
        {
            if (RootPFXCertificate == null)
            {
                throw new Exception("Root PFX certificate cannot be null");
            }
            if (PFXFilePassword == null || PFXFilePassword == "")
            {
                throw new Exception("Root certificate password must be set!");
            }
            Pkcs12Store pkcs12Store = new Pkcs12Store(new MemoryStream(RootPFXCertificate), PFXFilePassword.ToCharArray());
            string      current     = null;
            IEnumerator enumerator  = pkcs12Store.Aliases.GetEnumerator();

            do
            {
                if (!enumerator.MoveNext())
                {
                    break;
                }
                current = (string)enumerator.Current;
            }while (!pkcs12Store.IsKeyEntry(current));
            AsymmetricKeyParameter key = pkcs12Store.GetKey(current).Key;

            X509CertificateEntry[] certificateChain = pkcs12Store.GetCertificateChain(current);
            ArrayList arrayLists = new ArrayList();

            this.rootCert    = certificateChain[0].Certificate;
            this.rootKeyPair = new AsymmetricCipherKeyPair(this.rootCert.GetPublicKey(), key);
        }
Ejemplo n.º 28
0
                private (string certificate, string key) TransformPfx(IPasswordFinder passwordFinder)
                {
                    var certOutput = new StringWriter();
                    var keyOutput  = new StringWriter();

                    using (var input = File.OpenRead(CertificatePath))
                    {
                        var certWriter = new PemWriter(certOutput);
                        var keyWriter  = new PemWriter(keyOutput);
                        var store      = new Pkcs12Store(input, passwordFinder.GetPassword());
                        foreach (string alias in store.Aliases)
                        {
                            var cert = store.GetCertificate(alias);
                            if (cert != null)
                            {
                                certWriter.WriteObject(cert.Certificate);
                            }

                            var key = store.GetKey(alias);
                            if (key != null && key.Key.IsPrivate)
                            {
                                keyWriter.WriteObject(key.Key);
                            }
                        }
                    }

                    return(certOutput.ToString(), keyOutput.ToString());
                }
Ejemplo n.º 29
0
        /// <summary>
        /// Imports certificates and keys from a pkcs12-encoded stream.
        /// </summary>
        /// <remarks>
        /// Imports certificates and keys from a pkcs12-encoded stream.
        /// </remarks>
        /// <param name="stream">The raw certificate and key data.</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>
        public override void Import(Stream stream, string password)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (password == null)
            {
                throw new ArgumentNullException("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++)
                    {
                        certificates.Add(chain[i].Certificate);
                    }

                    keys.Add(chain[0].Certificate, entry.Key);
                }
                else if (pkcs12.IsCertificateEntry(alias))
                {
                    var entry = pkcs12.GetCertificate(alias);
                    certificates.Add(entry.Certificate);
                }
            }
        }
Ejemplo n.º 30
0
        static X509Certificate[] LoadPkcs12CertificateChain(string fileName, string password, out AsymmetricKeyParameter key)
        {
            using (var stream = File.OpenRead(fileName)) {
                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);

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

                        key = entry.Key;

                        var certificates = new X509Certificate[chain.Length];
                        for (int i = 0; i < chain.Length; i++)
                        {
                            certificates[i] = chain[i].Certificate;
                        }

                        return(certificates);
                    }
                }
            }

            throw new Exception("Failed to locate private key entry.");
        }