Ejemplo n.º 1
0
        static void signedPDF_detouched(string document)
        {
            //string certificate_dn = "C=RU, S=lenobl, L=spb, O=fil, OU=IT, CN=iks, E=iks@iks";  // Subject->Name

            string certificate_dn = "L=Санкт-Петербург, O=ООО Филберт, CN=iks, [email protected]";



            X509Store store = new X509Store("My", StoreLocation.CurrentUser);

            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
            X509Certificate2Collection found = store.Certificates.Find(
                X509FindType.FindBySubjectDistinguishedName, certificate_dn, true);


            if (found.Count == 0)
            {
                Console.Out.Write("Сертфикат [" + certificate_dn + "] не найден ");
                return;
            }

            if (found.Count > 1)
            {
                Console.WriteLine("Найдено более одного секретного ключа.");
                return;
            }



            X509Certificate2 certificate = found[0];

            CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider cert_key = certificate.PrivateKey as CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider;


            var cspParameters = new CspParameters();

            //копируем параметры csp из исходного контекста сертификата
            cspParameters.KeyContainerName = cert_key.CspKeyContainerInfo.KeyContainerName;
            cspParameters.ProviderType     = cert_key.CspKeyContainerInfo.ProviderType;
            cspParameters.ProviderName     = cert_key.CspKeyContainerInfo.ProviderName;
            cspParameters.Flags            = cert_key.CspKeyContainerInfo.MachineKeyStore
                              ? (CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore)
                              : (CspProviderFlags.UseExistingKey);
            cspParameters.KeyPassword = new SecureString();
            string pass = "******";

            foreach (var c in pass)
            {
                cspParameters.KeyPassword.AppendChar(c);
            }
            //создаем новый контекст сертификат, поскольку исходный открыт readonly
            certificate = new X509Certificate2(certificate.RawData);
            //задаем криптопровайдер с установленным паролем
            certificate.PrivateKey = new CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider(cspParameters);


            /////////////////////////читаем файл

            /*
             *          System.IO.StreamReader file = new System.IO.StreamReader("C:\\TEMP\\test.json");
             *
             *          string s = file.ReadToEnd();
             *                byte[] body = Encoding.Default.GetBytes(s);
             */


            /////////////////////////////   PDF  подпись ////////////////////////////////////////////////

            PdfReader reader = new PdfReader(document);


            string newSigned = Path.Combine(Path.GetDirectoryName(document) + @"\" + Path.GetFileNameWithoutExtension(document) + "_signed_.pdf");

            FileStream             signedPDF = new FileStream(newSigned, FileMode.Create, FileAccess.ReadWrite);
            PdfStamper             st        = PdfStamper.CreateSignature(reader, signedPDF, '\0', null, true);
            PdfSignatureAppearance sap       = st.SignatureAppearance;



            //  Создаем объект ContentInfo по сообщению.
            //  Это необходимо для создания объекта SignedCms.
            ContentInfo contentInfo = new ContentInfo(reader.Metadata);

            //  Создаем объект SignedCms по только что созданному
            //  объекту ContentInfo.
            //  SubjectIdentifierType установлен по умолчанию в
            //  IssuerAndSerialNumber.
            //  Свойство Detached устанавливаем явно в true, таким
            //  образом сообщение будет отделено от подписи.
            SignedCms signedCms = new SignedCms(contentInfo, true);

            //  Определяем подписывающего, объектом CmsSigner.
            CmsSigner cmsSigner = new CmsSigner(certificate);

            //  Подписываем CMS/PKCS #7 сообение.
            Console.Write("Вычисляем подпись сообщения для субъекта " +
                          "{0} ... ", certificate.SubjectName.Name);
            signedCms.ComputeSignature(cmsSigner);
            Console.WriteLine("Успешно.");

            //  Кодируем CMS/PKCS #7 подпись сообщения.
            byte [] signDetouched = signedCms.Encode();


            newSigned = Path.Combine(Path.GetDirectoryName(document) + @"\" + Path.GetFileNameWithoutExtension(document) + "_signed_Detouched.sig");


            // using (var fs = new FileStream(newSigned, FileMode.Create, FileAccess.ReadWrite))
            FileStream fs = new FileStream(newSigned, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

            fs.Write(signDetouched, 0, signDetouched.Length);

            fs.Close();



            /*
             * FileStream fs1 = File.Create(newSigned);
             * fs1.Close();
             * StreamWriter FS = new StreamWriter("./data.ns");
             */
        }
Ejemplo n.º 2
0
        static void signPDF(string document)
        {
            //string certificate_dn = "C=RU, S=lenobl, L=spb, O=fil, OU=IT, CN=iks, E=iks@iks";  // Subject->Name

            string certificate_dn = "L=Санкт-Петербург, O=ООО Филберт, CN=iks, [email protected]";



            X509Store store = new X509Store("My", StoreLocation.CurrentUser);

            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
            X509Certificate2Collection found = store.Certificates.Find(
                X509FindType.FindBySubjectDistinguishedName, certificate_dn, true);


            if (found.Count == 0)
            {
                Console.Out.Write("Сертфикат [" + certificate_dn + "] не найден ");
                return;
            }

            if (found.Count > 1)
            {
                Console.WriteLine("Найдено более одного секретного ключа.");
                return;
            }



            X509Certificate2 certificate = found[0];

            CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider cert_key = certificate.PrivateKey as CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider;


            var cspParameters = new CspParameters();

            //копируем параметры csp из исходного контекста сертификата
            cspParameters.KeyContainerName = cert_key.CspKeyContainerInfo.KeyContainerName;
            cspParameters.ProviderType     = cert_key.CspKeyContainerInfo.ProviderType;
            cspParameters.ProviderName     = cert_key.CspKeyContainerInfo.ProviderName;
            cspParameters.Flags            = cert_key.CspKeyContainerInfo.MachineKeyStore
                              ? (CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore)
                              : (CspProviderFlags.UseExistingKey);
            cspParameters.KeyPassword = new SecureString();
            string pass = "******";

            foreach (var c in pass)
            {
                cspParameters.KeyPassword.AppendChar(c);
            }
            //создаем новый контекст сертификат, поскольку исходный открыт readonly
            certificate = new X509Certificate2(certificate.RawData);
            //задаем криптопровайдер с установленным паролем
            certificate.PrivateKey = new CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider(cspParameters);


            /////////////////////////читаем файл

            /*
             *          System.IO.StreamReader file = new System.IO.StreamReader("C:\\TEMP\\test.json");
             *
             *          string s = file.ReadToEnd();
             *                byte[] body = Encoding.Default.GetBytes(s);
             */


            /////////////////////////////   PDF  подпись ////////////////////////////////////////////////

            PdfReader reader = new PdfReader(document);


            string newSigned = Path.Combine(Path.GetDirectoryName(document) + @"\" + Path.GetFileNameWithoutExtension(document) + "_signed" + Path.GetExtension(document));

            FileStream             signedPDF = new FileStream(newSigned, FileMode.Create, FileAccess.ReadWrite);
            PdfStamper             st        = PdfStamper.CreateSignature(reader, signedPDF, '\0', null, true);
            PdfSignatureAppearance sap       = st.SignatureAppearance;



            // Загружаем сертификат в объект iTextSharp
            X509CertificateParser parser = new X509CertificateParser();

            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] {
                parser.ReadCertificate(certificate.RawData)
            };

            sap.Certificate = parser.ReadCertificate(certificate.RawData);
            sap.Reason      = "I like to sign";
            sap.Location    = "Universe";
            sap.Acro6Layers = true;

            //sap.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription;
            sap.SignDate = DateTime.Now;

            // Выбираем подходящий тип фильтра
            PdfName filterName = new PdfName("CryptoPro PDF");

            // Создаем подпись
            PdfSignature dic = new PdfSignature(filterName, PdfName.ADBE_PKCS7_DETACHED);

            dic.Date = new PdfDate(sap.SignDate);
            dic.Name = "iks";
            if (sap.Reason != null)
            {
                dic.Reason = sap.Reason;
            }
            if (sap.Location != null)
            {
                dic.Location = sap.Location;
            }
            sap.CryptoDictionary = dic;

            int intCSize = 4000;
            Dictionary <PdfName, int> hashtable = new Dictionary <PdfName, int>();

            hashtable[PdfName.CONTENTS] = intCSize * 2 + 2;
            sap.PreClose(hashtable);
            Stream       s    = sap.GetRangeStream();
            MemoryStream ss   = new MemoryStream();
            int          read = 0;

            byte[] buff = new byte[8192];
            while ((read = s.Read(buff, 0, 8192)) > 0)
            {
                ss.Write(buff, 0, read);
            }



            //////////////////////////////////////////



            // Вычисляем подпись
            ContentInfo contentInfo = new ContentInfo(ss.ToArray());
            SignedCms   signedCms   = new SignedCms(contentInfo, true);
            CmsSigner   cmsSigner   = new CmsSigner(certificate);

            signedCms.ComputeSignature(cmsSigner, false);
            byte[] pk = signedCms.Encode();


            /*
             * // Помещаем подпись в документ
             * byte[] outc = new byte[intCSize];
             * PdfDictionary dic2 = new PdfDictionary();
             * Array.Copy(pk, 0, outc, 0, pk.Length);
             * dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
             * sap.Close(dic2);
             */


            Console.WriteLine(string.Format("Документ {0} успешно подписан на ключе {1} => {2}.",
                                            document, certificate.Subject, newSigned));

            /*
             * System.IO.StreamWriter sw = null;
             * System.IO.FileStream fs = new System.IO.FileStream("C:\\TEMP\\test_json_signed.json", System.IO.FileMode.Append, System.IO.FileAccess.Write);
             *
             *
             * sw = new System.IO.StreamWriter(fs, Encoding.GetEncoding(1251));
             * sw.WriteLine(Encoding.Default.GetString(pk));
             * sw.Close();
             *
             * fs.Dispose();
             * fs.Close();
             */


            // Помещаем подпись в документ
            byte[]        outc = new byte[intCSize];
            PdfDictionary dic2 = new PdfDictionary();

            Array.Copy(pk, 0, outc, 0, pk.Length);
            dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
            sap.Close(dic2);



            /////////////////////////////////////////////////////////////////////////////
        }
Ejemplo n.º 3
0
        static void signedPDF_detouched2(string document)
        {
            //string certificate_dn = "C=RU, S=lenobl, L=spb, O=fil, OU=IT, CN=iks, E=iks@iks";  // Subject->Name

            //  string certificate_dn = "L=Санкт-Петербург, O=ООО Филберт, CN=iks, [email protected]";

            /*
             *          string certificate_dn = "ОГРН=1107847250961, СНИЛС=11635484352, ИНН=007841430420, [email protected], O=ООО \"ФИЛБЕРТ\", T=Ведущий специалист, CN=ООО \"ФИЛБЕРТ\", " +
             *              "SN=Федорова, G=Надежда Александровна, C=RU, L=САНКТ-ПЕТЕРБУРГ, S=78 ГОРОД САНКТ-ПЕТЕРБУРГ, STREET=УЛИЦА МАРШАЛА ГОВОРОВА, ДОМ 35, КОРПУС 5, ЛИТ. Ж";
             *
             *
             */

            string certificate_dn = "5A4075D2A0AB688A22720C0C22A16CAD6565DE55"; //"‎01f7f2f000faab2f9b4423fad021e40f58";

            //  byte [] certificate_dn =  ASCIIEncoding.ASCII.GetBytes(ser);
            //{‎01, 0xf7, 0xf2, 0xf0, 0x00, 0xfa, 0xab, 0x2f, 0x9b, 0x44, 0x23, 0xfa, 0xd0, 0x21, 0xe4, 0x0f, 0x58 };



            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
            X509Certificate2Collection found = store.Certificates.Find(
                // X509FindType.FindBySubjectDistinguishedName, certificate_dn, true);
                X509FindType.FindByThumbprint, certificate_dn, validOnly: false);

            if (found.Count == 0)
            {
                Console.Out.Write("Сертфикат [" + certificate_dn + "] не найден ");
                return;
            }

            if (found.Count > 1)
            {
                Console.WriteLine("Найдено более одного секретного ключа.");
                return;
            }



            X509Certificate2 certificate = found[0];

            CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider cert_key = certificate.PrivateKey as CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider;


            var cspParameters = new CspParameters();

            //копируем параметры csp из исходного контекста сертификата
            cspParameters.KeyContainerName = cert_key.CspKeyContainerInfo.KeyContainerName;
            cspParameters.ProviderType     = cert_key.CspKeyContainerInfo.ProviderType;
            cspParameters.ProviderName     = cert_key.CspKeyContainerInfo.ProviderName;
            cspParameters.Flags            = cert_key.CspKeyContainerInfo.MachineKeyStore
                              ? (CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore)
                              : (CspProviderFlags.UseExistingKey);
            cspParameters.KeyPassword = new SecureString();
            string pass = "******";                    // "zZ123123";

            foreach (var c in pass)
            {
                cspParameters.KeyPassword.AppendChar(c);
            }
            //создаем новый контекст сертификат, поскольку исходный открыт readonly
            certificate = new X509Certificate2(certificate.RawData);
            //задаем криптопровайдер с установленным паролем
            certificate.PrivateKey = new CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider(cspParameters);


            /////////////////////////читаем файл

            System.IO.StreamReader file = new System.IO.StreamReader(document);



            var bytes = default(byte[]);

            using (var memstream = new MemoryStream())
            {
                file.BaseStream.CopyTo(memstream);
                bytes = memstream.ToArray();
            }



/*
 *          //  Переводим исходное сообщение в массив байтов.
 *          Encoding unicode = Encoding.Unicode;
 *          byte[] msgBytes = unicode.GetBytes(string.Empty);
 */


            /////////////////////////////   PDF  подпись ////////////////////////////////////////////////



            //  Создаем объект ContentInfo по сообщению.
            //  Это необходимо для создания объекта SignedCms.
            ContentInfo contentInfo = new ContentInfo(bytes);

            //  Создаем объект SignedCms по только что созданному
            //  объекту ContentInfo.
            //  SubjectIdentifierType установлен по умолчанию в
            //  IssuerAndSerialNumber.
            //  Свойство Detached устанавливаем явно в true, таким
            //  образом сообщение будет отделено от подписи.
            SignedCms signedCms = new SignedCms(contentInfo, true);

            //  Определяем подписывающего, объектом CmsSigner.
            CmsSigner cmsSigner = new CmsSigner(certificate);

            //  Подписываем CMS/PKCS #7 сообение.
            Console.Write("Вычисляем подпись сообщения для субъекта " +
                          "{0} ... ", certificate.SubjectName.Name);
            signedCms.ComputeSignature(cmsSigner);
            Console.WriteLine("Успешно.");

            //  Кодируем CMS/PKCS #7 подпись сообщения.
            byte[] signDetouched = signedCms.Encode();


            string newSigned = Path.Combine(Path.GetDirectoryName(document) + @"\" + Path.GetFileNameWithoutExtension(document) + "_signed_Detouched2.sig");


            // using (var fs = new FileStream(newSigned, FileMode.Create, FileAccess.ReadWrite))
            FileStream fs = new FileStream(newSigned, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

            fs.Write(signDetouched, 0, signDetouched.Length);

            fs.Close();



            /*
             * FileStream fs1 = File.Create(newSigned);
             * fs1.Close();
             * StreamWriter FS = new StreamWriter("./data.ns");
             */
        }