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 void testSignSimpleContainerECDsa()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";
            string storePath    = @"..\..\..\..\simple\keystore\test1234.p12";
            string storePass    = "******";
            string storeAlias   = "ECDSAkey";

            SystemCertificates.X509Certificate2Collection pkcs12 = new SystemCertificates.X509Certificate2Collection();
            pkcs12.Import(storePath, storePass, SystemCertificates.X509KeyStorageFlags.DefaultKeySet);
            SystemCertificates.X509Certificate2 certificate = null;
            foreach (SystemCertificates.X509Certificate2 aCertificate in pkcs12)
            {
                if (storeAlias.Equals(aCertificate.FriendlyName, StringComparison.InvariantCultureIgnoreCase))
                {
                    certificate = aCertificate;
                    break;
                }
            }
            Assert.NotNull(certificate, "Key with alias {0} not found.", storeAlias);

            X509Certificate2SignatureContainer signature = new X509Certificate2SignatureContainer(certificate, signer => {
                signer.DigestAlgorithm = Oid.FromFriendlyName("SHA512", OidGroup.HashAlgorithm);
            });

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

                    pdfSigner.SignExternalContainer(signature, 8192);
                }
        }
Beispiel #3
0
        public virtual void CalcHashOnDocCreationThenDeferredSignTest01()
        {
            String input       = sourceFolder + "helloWorldDoc.pdf";
            String outFileName = destinationFolder + "calcHashOnDocCreationThenDeferredSignTest01.pdf";
            String cmpFileName = sourceFolder + "cmp_calcHashOnDocCreationThenDeferredSignTest01.pdf";
            // pre-calculate hash on creating pre-signed PDF
            String       sigFieldName  = "DeferredSignature1";
            PdfName      filter        = PdfName.Adobe_PPKLite;
            PdfName      subFilter     = PdfName.Adbe_pkcs7_detached;
            int          estimatedSize = 8192;
            PdfReader    reader        = new PdfReader(input);
            MemoryStream baos          = new MemoryStream();
            PdfSigner    signer        = new PdfSigner(reader, baos, new StampingProperties());

            signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetLayer2Text("Signature field which signing is deferred.").SetPageRect(new Rectangle(36, 600,
                                                                                                             200, 100)).SetPageNumber(1);
            signer.SetFieldName(sigFieldName);
            SignDeferredTest.DigestCalcBlankSigner external = new SignDeferredTest.DigestCalcBlankSigner(filter, subFilter
                                                                                                         );
            signer.SignExternalContainer(external, estimatedSize);
            byte[] docBytesHash   = external.GetDocBytesHash();
            byte[] preSignedBytes = baos.ToArray();
            // sign the hash
            String signCertFileName = certsSrc + "signCertRsa01.p12";

            X509Certificate[] signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);

            byte[] cmsSignature = SignDocBytesHash(docBytesHash, signPrivateKey, signChain);
            // fill the signature to the presigned document
            SignDeferredTest.ReadySignatureSigner extSigContainer = new SignDeferredTest.ReadySignatureSigner(cmsSignature
                                                                                                              );
            PdfDocument docToSign = new PdfDocument(new PdfReader(new MemoryStream(preSignedBytes)));
            FileStream  outStream = new FileStream(outFileName, FileMode.Create);

            PdfSigner.SignDeferred(docToSign, sigFieldName, outStream, extSigContainer);
            docToSign.Close();
            outStream.Dispose();
            // validate result
            PadesSigTest.BasicCheckSignedDoc(outFileName, sigFieldName);
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outFileName, cmpFileName, destinationFolder
                                                                            , null));
        }
Beispiel #4
0
        public static byte[] EmptySignature()
        {
            byte[] Hash = null;

            PdfReader reader = new PdfReader(src);

            using (FileStream fout = new FileStream(temp, FileMode.Create))
            {
                StampingProperties sp = new StampingProperties();
                sp.UseAppendMode();

                PdfSigner pdfSigner = new PdfSigner(reader, fout, sp);
                pdfSigner.SetFieldName("Signature");

                PdfSignatureAppearance appearance = pdfSigner.GetSignatureAppearance();
                appearance.SetPageNumber(1);
                appearance.SetPageRect(new Rectangle(100, 100));
                appearance.SetLocation("Varazdin");

                SHA256 sha           = new SHA256CryptoServiceProvider();
                String hashAlgorithm = DigestAlgorithms.SHA256;

                var externalSignature = new ExternalHashingSignatureContainer(PdfName.Adobe_PPKLite,
                                                                              PdfName.Adbe_pkcs7_detached);
                pdfSigner.SignExternalContainer(externalSignature, 8192);
                digest = externalSignature.Hash;

                var base64digest = Convert.ToBase64String(digest);
            }

            PdfReader  readerFout       = new PdfReader(temp);
            FileStream destPdf          = new FileStream(dest, FileMode.Create);
            PdfSigner  pdfSigner2       = new PdfSigner(readerFout, destPdf, new StampingProperties());
            var        hashBase65       = Convert.ToBase64String(digest);
            string     signedBase64Hash = String.Empty;

            byte[] signedHash = ConvertToBytes(signedBase64Hash);
            var    container  = new MyExternalSignatureContainer(signedHash, GetChains(), Hash);

            pdfSigner2.SignExternalContainer(container, 8192);

            return(Hash);
        }
Beispiel #5
0
        /// <summary>
        /// Method that creates a temporary pdf for calating the hash that must be sent to AMA for signing
        /// </summary>
        /// <param name="signingInformation">Information about the signature and its appearance</param>
        /// <returns>Information with the hashes required for signing and completing the retrieved signature injection</returns>
        public HashesForSigning CreateTemporaryPdfForSigning(SigningInformation signingInformation)
        {
            var pdfSigner = new PdfSigner(new PdfReader(signingInformation.PathToPdf),
                                          new FileStream(signingInformation.PathToIntermediaryPdf, FileMode.Create),
                                          new StampingProperties());

            pdfSigner.SetFieldName(_signatureFieldname);


            var appearance = pdfSigner.GetSignatureAppearance();

            appearance.SetPageRect(new Rectangle(10,
                                                 750,
                                                 150,
                                                 50))
            .SetPageNumber(signingInformation.PageNumber)
            .SetLayer2FontSize(6f)
            .SetReason(signingInformation.Reason)
            .SetLocation(signingInformation.Location)
            .SetLayer2Text(BuildVisibleInformation(signingInformation.Reason, signingInformation.Location))
            .SetCertificate(_userCertificateChain[0]);

            if (signingInformation.Logo != null)
            {
                appearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION)
                .SetSignatureGraphic(signingInformation.Logo);
            }


            var crlBytesList = GetCrlByteList();

            var ocspBytesList = GetOcspBytesList();


            var container = new PrefareForAmaSigningContainer(_userCertificateChain, crlBytesList, ocspBytesList);

            pdfSigner.SignExternalContainer(container, EstimateContainerSize(crlBytesList)); // add size for timestamp in signature

            return(new HashesForSigning(container.HashToBeSignedByAma, container.NakedHash));
        }
Beispiel #6
0
        public virtual void PrepareDocForSignDeferredTest()
        {
            String    input         = sourceFolder + "helloWorldDoc.pdf";
            String    output        = destinationFolder + "newTemplateForSignDeferred.pdf";
            String    sigFieldName  = "DeferredSignature1";
            PdfName   filter        = PdfName.Adobe_PPKLite;
            PdfName   subFilter     = PdfName.Adbe_pkcs7_detached;
            int       estimatedSize = 8192;
            PdfReader reader        = new PdfReader(input);
            PdfSigner signer        = new PdfSigner(reader, new FileStream(output, FileMode.Create), new StampingProperties()
                                                    );
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetLayer2Text("Signature field which signing is deferred.").SetPageRect(new Rectangle(36, 600,
                                                                                                             200, 100)).SetPageNumber(1);
            signer.SetFieldName(sigFieldName);
            IExternalSignatureContainer external = new ExternalBlankSignatureContainer(filter, subFilter);

            signer.SignExternalContainer(external, estimatedSize);
            // validate result
            ValidateTemplateForSignedDeferredResult(output, sigFieldName, filter, subFilter, estimatedSize);
        }
Beispiel #7
0
        /// <summary>
        /// Methods which returns base64 digested PDF.
        /// </summary>
        /// <param name="unsignedPdf">Path to pdf which needs to be signed</param>
        /// <param name="tempPdf">Path to temporary pdf</param>
        /// <param name="signatureFieldName">Name of field</param>
        /// <returns></returns>
        public static string GetBytesToSign(string unsignedPdf, string tempPdf, string signatureFieldName)
        {
            if (File.Exists(tempPdf))
            {
                File.Delete(tempPdf);
            }

            using (PdfReader reader = new PdfReader(unsignedPdf))
            {
                using (FileStream os = File.OpenWrite(tempPdf))
                {
                    StampingProperties sp = new StampingProperties();
                    sp.UseAppendMode();

                    PdfSigner pdfSigner = new PdfSigner(reader, os, sp);
                    pdfSigner.SetFieldName(signatureFieldName);

                    PdfSignatureAppearance appearance = pdfSigner.GetSignatureAppearance();
                    appearance.SetPageNumber(1);
                    appearance.SetPageRect(new Rectangle(100, 100));
                    appearance.SetLocation("Varazdin");

                    //Creating container for emty signature, with atrivute where digest is calculated.
                    //ExternalHashingSignatureContainer external = new ExternalHashingSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_pkcs7_detached);
                    //pdfSigner.SignExternalContainer(external, 8192);
                    //hash = external.Hash;

                    //Creating container for empty signature.
                    IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_x509_rsa_sha1);
                    pdfSigner.SignExternalContainer(external, 8192);

                    //Digest from created new temporary PDF with empty space for signature.
                    FileStream oso = File.OpenRead(temp);
                    hash = DigestAlgorithms.Digest(oso, DigestAlgorithms.SHA256);

                    return(Convert.ToBase64String(hash));
                }
            }
        }
Beispiel #8
0
        public void testSignSimpleEcdsaExternal()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";

            string keyId = "alias/SigningExamples-ECC_NIST_P256";
            Func <System.Collections.Generic.List <string>, string> selector = list => list.Find(name => name.StartsWith("ECDSA_SHA_256"));

            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate2 = CertificateUtils.generateSelfSignedCertificate(
                keyId,
                "CN=AWS KMS PDF Signing Test ECDSA,OU=mkl tests,O=mkl",
                selector
                );
            X509Certificate          certificate = new X509Certificate(X509CertificateStructure.GetInstance(certificate2.RawData));
            AwsKmsSignatureContainer signature   = new AwsKmsSignatureContainer(certificate, keyId, selector);

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

                    pdfSigner.SignExternalContainer(signature, 8192);
                }
        }
Beispiel #9
0
        public void EmptySignature(String src, String dest, String fieldname, X509Certificate[] chain)
        {
            PdfReader reader = new PdfReader(src);
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties());

            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance
            .SetPageRect(new Rectangle(36, 748, 200, 100))
            .SetPageNumber(1)
            .SetCertificate(chain[0]);
            signer.SetFieldName(fieldname);

            /* ExternalBlankSignatureContainer constructor will create the PdfDictionary for the signature
             * information and will insert the /Filter and /SubFilter values into this dictionary.
             * It will leave just a blank placeholder for the signature that is to be inserted later.
             */
            IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite,
                                                                                       PdfName.Adbe_pkcs7_detached);

            // Sign the document using an external container
            // 8192 is the size of the empty signature placeholder.
            signer.SignExternalContainer(external, 8192);
        }
        public static byte[] SignPDFStream(MemoryStream source, string rootPath)
        {
            collection = new X509Certificate2Collection();
            collection.Import(GsConfig.GetSslCertificatePath(rootPath), GsConfig.KeyPassword,
                              X509KeyStorageFlags.DefaultKeySet);
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;

            //get JSON access token
            JObject access = Login(baseURL, GsConfig.ApiKey, GsConfig.ApiSecret);

            //get JSON with id/certificate/ocsp response
            JObject identity = Identity(baseURL, access);
            String  cert     = (String)identity.GetValue("signing_cert");
            String  id       = (String)identity.GetValue("id");
            String  oc1      = (String)identity.GetValue("ocsp_response");
            JObject path     = CertificatePath(baseURL, access);
            String  ca       = (String)path.GetValue("path");

            //Create Certificate chain
            X509Certificate[] chain = CreateChain(cert, ca);

            //create empty signature
            PdfReader reader = new PdfReader(source);

            byte[] fileArray = null;
            using (MemoryStream os = new MemoryStream()) {
                PdfSigner stamper = new PdfSigner(reader, os, new StampingProperties());

                PdfSignatureAppearance appearance = stamper.GetSignatureAppearance();
                appearance.SetPageRect(new Rectangle(0, 0, 0, 0));
                stamper.SetFieldName(fieldName);

                IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite,
                                                                                           PdfName.Adbe_pkcs7_detached);

                stamper.SignExternalContainer(external, 8192);

                fileArray = os.ToArray();
            }

            using (var tempStream = new MemoryStream(fileArray)) {
                PdfReader tempReader = new PdfReader(tempStream);

                byte[]   oc2      = Convert.FromBase64String(oc1);
                OcspResp ocspResp = new OcspResp(oc2);

                IExternalSignatureContainer gsContainer = new MyExternalSignatureContainer(id, access, chain, ocspResp);
                using (MemoryStream destination = new MemoryStream()) {
                    PdfSigner signer = new PdfSigner(tempReader, destination, new StampingProperties());
                    PdfSigner.SignDeferred(signer.GetDocument(), fieldName, destination, gsContainer);

                    fileArray = destination.ToArray();
                }
            }

            using (MemoryStream LTV = new MemoryStream())
                using (var newSource = new MemoryStream(fileArray)) {
                    addLTVToStream(newSource, LTV, new OcspClientBouncyCastle(null),
                                   new CrlClientOnline(), LtvVerification.Level.OCSP_CRL,
                                   LtvVerification.Level.OCSP_CRL);

                    return(LTV.ToArray());
                }
        }