public ActionResult Complete(BatchSignatureCompleteRequest request)
        {
            byte[] signatureContent;

            // Recover the "transfer data" content stored in a temporary file.
            byte[] transferDataContent;
            if (!StorageMock.TryGetFile(request.TransferDataFileId, out transferDataContent))
            {
                return(HttpNotFound());
            }

            // Instantiate a PadesSigner class
            var padesSigner = new PadesSigner();

            // Set the signature policy.
            padesSigner.SetPolicy(GetSignaturePolicy());

            // Set the signature computed on the client-side, along with the "transfer data" recovered from a temporary file
            padesSigner.SetPreComputedSignature(request.Signature, transferDataContent);

            // Call ComputeSignature(), which does all the work, including validation of the signer's certificate and of the
            // resulting signature
            padesSigner.ComputeSignature();

            // Get the signed PDF as an array of bytes
            signatureContent = padesSigner.GetPadesSignature();

            return(Json(new BatchSignatureCompleteResponse()
            {
                SignedFileId = StorageMock.Store(signatureContent, ".pdf")
            }));
        }
        private void completeSignature()
        {
            byte[] signatureContent;

            try {
                // Retrieve the "transfer data" stored on the initial step (see method startNextSignature()).
                var transferData = Storage.GetFile(TransferDataFileIdField.Value);

                // We won't be needing the "transfer data" anymore, so we delete it.
                Storage.DeleteFile(TransferDataFileIdField.Value);

                // Instantiate a PadesSigner class.
                var padesSigner = new PadesSigner();

                // Set the signature policy, exactly like in the Start method.
                padesSigner.SetPolicy(getSignaturePolicy());

                // Set the signature computed on the client-side, along with the "transfer data".
                padesSigner.SetPreComputedSignature(Convert.FromBase64String(SignatureField.Value), transferData);

                // Call ComputeSignature(), which does all the work, including validation of the signer's
                // certificate and of the resulting signature.
                padesSigner.ComputeSignature();

                // Get the signed PDF as an array of bytes.
                signatureContent = padesSigner.GetPadesSignature();
            }
            catch (ValidationException ex) {
                // One or more validations failed. We log the error and update the page with a summary of what
                // happened to this document.
                logger.Error(ex, "Validation error completing the signature of a batch document");
                setValidationError(ex.ValidationResults);
                return;
            }
            catch (Exception ex) {
                // An error has occurred. We log the error and update the page with a summary of what happened to
                // this document.
                logger.Error(ex, "Error completing the signature of a batch document");
                setError(ex.Message);
                return;
            }

            // Store the signed file.
            var file = Storage.StoreFile(signatureContent, ".pdf");

            // Update the page with a link to the signed file.
            var docItem = DocumentsListView.Items[DocumentIndex];

            docItem.DataItem = new DocumentItem()
            {
                Id           = DocumentIds[DocumentIndex],
                DownloadLink = "Download?file=" + file
            };
            docItem.DataBind();
        }
Example #3
0
        static void Main(string[] args)
        {
            // This is a TRIAL token. It will expire at 31/08/2020.
            PkiConfig.LoadLicense(Convert.FromBase64String("AxAAIIy8jc59Q0q95BZrL57K5hEAUEtJIFN1aXRlIFNhbXBsZXMIAAD0Ze31HdgICACAXwryrU7YCAAAAAAAAAQAfwAAAAABL2+ls7EW5LHD/tEetd49d0JpmU7pXEjhH0pU1ZSp5qjvKxL8c8PZz6ODTf68+lfQtXkKaRlQH6hu7VTSU3fvhCmZovDB5ruKqJPn+MQRDBbS8Wkr/meVo9LBS+3NFOky+EY43ebFoFxTbVZl2lCjb0DuskJiZGuHOBJ1v2XpGdKCmh1c1LmMvpc+OPegzNuMCXoEzSN9DdRtKnDzRxvOnvPglCX9+oV89LWsmVzonRp1a+tluqa8Ron9pFdHI9cWBElcXpmwXbKbmP0Sy5yYbYpE+rYsNgD5sV/FwF8uOxGWA0/mRWLZlO3OcGWoYo7qBBDmCUApAcRmZR3tXqhELQ=="));

            var connection = new ConnectionBuilder()
                             .WithLogging()
                             .Build();

            // "List Certificates" operation.
            connection.On <string, List <CertificateModel> >("list-certs", _ => {
                var store = WindowsCertificateStore.LoadPersonalCurrentUser();

                return(store.GetCertificatesWithKey().Select(c => new CertificateModel(c.Certificate)).ToList());
            });

            // "Sign a PDF" operation.
            connection.On <SignatureRequestModel, string>("sign-pdf", request => {
                var signer = new PadesSigner();

                var store       = WindowsCertificateStore.LoadPersonalCurrentUser();
                var signingCert = store.GetCertificatesWithKey().First(c => c.Certificate.ThumbprintSHA256.SequenceEqual(request.CertThumb));

                signer.SetSigningCertificate(signingCert);
                signer.SetPdfToSign(request.FileToSign);

                var trustArbitrator = new LinkedTrustArbitrator(TrustArbitrators.PkiBrazil, TrustArbitrators.Windows);
                // For development purposes, we also trust in Lacuna Software's test certificates.
                var lacunaRoot = Lacuna.Pki.PKCertificate.Decode(Convert.FromBase64String("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"));
                // COMMENT the line below before production release
                trustArbitrator.Add(new TrustedRoots(lacunaRoot));

                signer.SetPolicy(PadesPoliciesForGeneration.GetPadesBasic(trustArbitrator));
                signer.ComputeSignature();

                byte[] signedPdf = signer.GetPadesSignature();

                var tempLocation = Path.GetTempFileName();
                File.WriteAllBytes(tempLocation, signedPdf);

                return(tempLocation);
            });

            // Acknowledges that the connection is running.
            connection.On <string, string>("ping", argument => "pong");


            // wait for incoming requests
            connection.Listen();
        }
        public ActionResult Complete(SignatureCompleteModel model)
        {
            byte[] signatureContent;

            try {
                // Recover the "transfer data" content stored in a temporary file.
                byte[] transferDataContent;
                if (!StorageMock.TryGetFile(model.TransferDataFileId, out transferDataContent))
                {
                    return(HttpNotFound());
                }

                // Get an instance of the PadesSigner class.
                var padesSigner = new PadesSigner();

                // Set the signature policy.
                padesSigner.SetPolicy(GetSignaturePolicy());

                // Set the signature computed on the client-side, along with the "transfer data" (rendered in a hidden field, see the view)
                padesSigner.SetPreComputedSignature(model.Signature, transferDataContent);

                // Call ComputeSignature(), which does all the work, including validation of the signer's certificate and of the resulting signature
                padesSigner.ComputeSignature();

                // Get the signed PDF as an array of bytes
                signatureContent = padesSigner.GetPadesSignature();
            } catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate is revoked.
                ModelState.AddModelError("", ex.ValidationResults.ToString());
                // Return userfile to continue the signature with the same file.
                return(View(model));
            }

            // On the next step (SignatureInfo action), we'll render the following information:
            // - The filename to be available to download in next action.
            // - The signer's certificate information to be rendered.
            // We'll store these values on TempData, which is a dictionary shared between actions.
            TempData["SignatureInfoModel"] = new SignatureInfoModel()
            {
                // Store the signature file on the folder "App_Data/" and redirects to the SignatureInfo action with the filename.
                // With this filename, it can show a link to download the signature file.
                File = StorageMock.Store(signatureContent, ".pdf")
            };

            return(RedirectToAction("SignatureInfo"));
        }
Example #5
0
        protected void SubmitSignatureButton_Click(object sender, EventArgs e)
        {
            byte[] signatureContent;

            try {
                // Retrieve the "transfer data" stored on the initial step (see method startNextSignature()).
                var transferData = Storage.GetFile(TransferDataFileIdField.Value);

                // We won't be needing the "transfer data" anymore, so we delete it.
                Storage.DeleteFile(TransferDataFileIdField.Value);

                // Instantiate a PadesSigner class.
                var padesSigner = new PadesSigner();

                // Set the signature policy, exactly like in the Start method.
                padesSigner.SetPolicy(getSignaturePolicy());

                // Set the signature computed on the client-side, along with the "transfer data".
                padesSigner.SetPreComputedSignature(Convert.FromBase64String(SignatureField.Value), transferData);

                // Call ComputeSignature(), which does all the work, including validation of the signer's
                // certificate and of the resulting signature.
                padesSigner.ComputeSignature();

                // Get the signed PDF as an array of bytes.
                signatureContent = padesSigner.GetPadesSignature();
            }
            catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate
                // is revoked.
                ex.ValidationResults.Errors.ForEach(ve => ModelState.AddModelError("", ve.ToString()));
                CertificateField.Value = "";
                ToSignHashField.Value  = "";
                return;
            }

            // Pass the following fields to be used on PadesSignatureInfo page:
            // - The signature file will be stored on the folder "App_Data/". Its name will be passed by
            //   SignatureFile field.
            // - The user's certificate
            this.SignatureFile = Storage.StoreFile(signatureContent, ".pdf");
            this.Certificate   = PKCertificate.Decode(Convert.FromBase64String(CertificateField.Value));

            Server.Transfer("PadesSignatureInfo.aspx");
        }
Example #6
0
        public void Sign()
        {
            if (string.IsNullOrEmpty(PdfPath))
            {
                MessageBox.Show("Please choose a PDF file sign");
                return;
            }
            if (!File.Exists(PdfPath))
            {
                MessageBox.Show("File not found: " + PdfPath);
                return;
            }
            if (SelectedCertificate == null)
            {
                MessageBox.Show("Please choose a certificate to sign the PDF");
                return;
            }
            if (Width <= 0 || Height <= 0 || Bottom <= 0 || Left <= 0)
            {
                MessageBox.Show("Please fill all coordinates with positive numbers");
                return;
            }

            try {
                var signer = new PadesSigner();                                                                              // Instantiate the PDF signer
                signer.SetSigningCertificate(selectedCertificate.CertificateWithKey);                                        // certificate with private key associated
                signer.SetPdfToSign(PdfPath);                                                                                // PDF file path
                signer.SetPolicy(PadesPoliciesForGeneration.GetPadesBasic(App.GetTrustArbitrator()));                        // Basic signature policy with the selected trust arbitrator
                signer.SetVisualRepresentation(getVisualRepresentation(selectedCertificate.CertificateWithKey.Certificate)); // Signature visual representation
                signer.ComputeSignature();                                                                                   // computes the signature
                byte[] signedPdf = signer.GetPadesSignature();                                                               // return the signed PDF bytes

                // saving signed PDF file
                var savePath = getSaveFilePath();
                if (!string.IsNullOrEmpty(savePath))
                {
                    File.WriteAllBytes(savePath, signedPdf);
                    Process.Start(savePath);
                }
            } catch (ValidationException ex) {
                new ValidationResultsDialog("Validation failed", ex.ValidationResults).ShowDialog();
            } catch (Exception ex) {
                MessageBox.Show($"Error while signing PDF\r\n\r\n{ex}");
            }
        }
        public IHttpActionResult Complete(SignatureCompleteRequest request)
        {
            byte[] signatureContent;

            try {
                // Retrieve the "transfer data" stored on the initial step (see Start action)
                var transferData = Storage.GetFile(request.TransferDataFileId);

                // We won't be needing the "transfer data" anymore, so we delte it
                Storage.DeleteFile(request.TransferDataFileId);

                // Instantiate a PadesSigner class
                var padesSigner = new PadesSigner();

                // Set the signature policy, exactly like in the Start method
                padesSigner.SetPolicy(getSignaturePolicy());

                // Set the signature computed on the client-side, along with the "transfer data"
                padesSigner.SetPreComputedSignature(request.Signature, transferData);

                // Call ComputeSignature(), which does all the work, including validation of the signer's certificate and of the resulting signature
                padesSigner.ComputeSignature();

                // Get the signed PDF as an array of bytes
                signatureContent = padesSigner.GetPadesSignature();
            } catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate is revoked.
                return(new ResponseMessageResult(Request.CreateResponse(HttpStatusCode.BadRequest, new ValidationErrorModel(ex.ValidationResults))));
            }

            // Pass the following fields to be used on signature-results template:
            // - The signature file will be stored on the folder "App_Data/". Its name will be passed by Filename field.
            // - The user's certificate
            var response = new SignatureCompleteResponse()
            {
                Filename    = Storage.StoreFile(signatureContent, ".pdf"),
                Certificate = new CertificateModel(PKCertificate.Decode(request.Certificate))
            };

            return(Ok(response));
        }
Example #8
0
        public IHttpActionResult Complete(BatchSignatureCompleteRequest request)
        {
            byte[] signatureContent;

            try {
                // Recover the "transfer data" content stored in a temporary file
                string extension;
                byte[] transferDataContent;
                if (!Storage.TryGetFile(request.TransferDataFileId, out transferDataContent, out extension))
                {
                    return(NotFound());
                }

                // Instantiate a PadesSigner class
                var padesSigner = new PadesSigner();

                // Set the signature policy, exactly like in the Start method
                padesSigner.SetPolicy(getSignaturePolicy());

                // Set the signature computed on the client-side, along with the "transfer data" recovered from a temporary file
                padesSigner.SetPreComputedSignature(request.Signature, transferDataContent);

                // Call ComputeSignature(), which does all the work, including validation of the signer's certificate and of the
                // resulting signature
                padesSigner.ComputeSignature();

                // Get the signed PDF as an array of bytes
                signatureContent = padesSigner.GetPadesSignature();
            }
            catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate is revoked.
                var message = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ValidationResults.ToString());
                return(ResponseMessage(message));
            }

            return(Ok(new BatchSignatureCompleteResponse()
            {
                SignedFileId = Storage.StoreFile(signatureContent, ".pdf")
            }));
        }
        public ActionResult Complete(SignatureCompleteModel model)
        {
            byte[] signatureContent;

            try {
                // Instantiate a PadesSigner class
                var padesSigner = new PadesSigner();

                // Set the signature policy, exactly like in the Start method
                padesSigner.SetPolicy(getSignaturePolicy());

                // Set the signature computed on the client-side, along with the "transfer data" (rendered in a hidden field, see the view)
                padesSigner.SetPreComputedSignature(model.Signature, model.TransferData);

                // Call ComputeSignature(), which does all the work, including validation of the signer's certificate and of the resulting signature
                padesSigner.ComputeSignature();

                // Get the signed PDF as an array of bytes
                signatureContent = padesSigner.GetPadesSignature();
            } catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate is revoked.
                ModelState.AddModelError("", ex.ValidationResults.ToString());
                return(View());
            }

            // On the next step (SignatureInfo action), we'll render the following information:]
            // - The filename to be available to download in next action.
            // - The signer's certificate information to be rendered.
            // We'll store these values on TempData, which is a dictionary shared between actions.
            TempData["SignatureInfoModel"] = new SignatureInfoModel()
            {
                // Store the signature file on the folder "App_Data/" and redirects to the SignatureInfo action with the filename.
                // With this filename, it can show a link to download the signature file.
                Filename = Storage.StoreFile(signatureContent, ".pdf"),
                UserCert = PKCertificate.Decode(model.CertContent)
            };

            return(RedirectToAction("SignatureInfo"));
        }
Example #10
0
        private static bool SignFile(string file, PKCertificateWithKey certWithKey, PadesPolicySpec policy, PadesVisualRepresentation2 visual, Metadata metadata, string outputDir, string outputName = null)
        {
            var documentoToSign = File.ReadAllBytes(file);

            if (metadata != null)
            {
                using (var buffer = new MemoryStream())
                {
                    using (var stream = new MemoryStream(documentoToSign))
                    {
                        DoConvertToPdfA(stream, metadata, buffer);
                    }
                    documentoToSign = buffer.ToArray();
                }
            }

            var signer = new PadesSigner();

            signer.SetSigningCertificate(certWithKey);
            signer.SetPdfToSign(documentoToSign);
            signer.SetPolicy(policy);
            signer.SetVisualRepresentation(visual);
            signer.SetCertificateValidationConfigurator(ConfigureNoValidation);
            if (string.IsNullOrWhiteSpace(outputName))
            {
                outputName = Path.GetFileName(file);
            }
            try {
                signer.ComputeSignature();
                var signed = signer.GetPadesSignature();
                File.WriteAllBytes(Path.Combine(outputDir, outputName), signed);
            } catch (Exception exception) {
                Log(exception.ToString(), file);
                return(false);
            }
            return(true);
        }
Example #11
0
        public async Task <IActionResult> Post([FromBody] SignatureRequest request)
        {
            // 1. Retrieve key using certId stored on your database.
            byte[] pkcs12;
            try {
                pkcs12 = await _azureKeyVaultStore.GetPkcs12Async(request.CertId);
            } catch (InvalidIdentifierException ex) {
                return(UnprocessableEntity(new ErrorModel()
                {
                    Code = ErrorCodes.InvalidIdentifier,
                    Message = ex.Message,
                }));
            }

            // 2. Open PKCS#12, verifying valid of the provided password.
            Pkcs12CertificateStore store;

            try {
                store = Pkcs12CertificateStore.Load(pkcs12, request.Pkcs12Password);
            } catch (IncorrectPinException ex) {
                return(UnprocessableEntity(new ErrorModel()
                {
                    Code = ErrorCodes.InvalidPIN,
                    Message = ex.Message,
                }));
            }

            // 3. Retrieve certification info (include its key).
            var certs = store.GetCertificatesWithKey();

            if (!certs.Any())
            {
                return(UnprocessableEntity(new ErrorModel()
                {
                    Code = ErrorCodes.InvalidPkcs12,
                    Message = "The provided PKCS#12 file is not valid",
                }));
            }
            var cert = certs.First();

            // 4. Perform signature.
            var signer = new PadesSigner();

            signer.SetSigningCertificate(cert);
            signer.SetPdfToSign(Path.Combine(_webHostEnvironment.ContentRootPath, "Resources", "SamplePdf.pdf"));
            signer.SetPolicy(PadesPoliciesForGeneration.GetPadesBasic());
            signer.SetVisualRepresentation(GetVisualRepresentation(cert.Certificate));
            signer.ComputeSignature();
            byte[] signedPdf = signer.GetPadesSignature();

            // 5. Store signature file.
            if (!System.IO.File.Exists(Path.Combine(_webHostEnvironment.ContentRootPath, "App_Data")))
            {
                Directory.CreateDirectory(Path.Combine(_webHostEnvironment.ContentRootPath, "App_Data"));
            }
            var fileId = Guid.NewGuid() + ".pdf";

            System.IO.File.WriteAllBytes(Path.Combine(_webHostEnvironment.ContentRootPath, "App_Data", fileId), signedPdf);

            return(Ok(new SignatureResponse()
            {
                FileId = fileId,
            }));
        }
Example #12
0
        /**
         * GET /PadesCloudOauthSdk/Complete
         *
         * This action will complete the authentication process and create a signature using a session
         * token returned by user. Also, we recover the parameter "customState" containing the id of the
         * file that will be signed.
         */
        public async Task <ActionResult> Complete(string code, string state)
        {
            byte[] signatureContent;
            PKCertificateWithKey signingCertificate;

            try {
                // Get an instance of the TrustServiceManager class, responsible for communicating with PSCs
                // and handling the OAuth flow.
                var manager = Util.GetTrustServicesManager();

                // Complete the authentication process, recovering the session info to be used on the
                // signature and the custom state (fileId).
                var completeAuthResult = await manager.CompleteAuthAsync(code, state);

                // Recover file to be sigend on custom state parameter.
                var userfile = completeAuthResult.CustomState;

                // Verify if the userfile exists and get its absolute path.
                string userfilePath;
                if (!StorageMock.TryGetFile(userfile, out userfilePath))
                {
                    return(HttpNotFound());
                }

                // Get an instance of the PadesSigner class, responsible for receiving the signature elements
                // and performing the local signature.
                var signer = new PadesSigner();

                // Set signature policy.
                signer.SetPolicy(GetSignaturePolicy());

                // Set file to be signed.
                signer.SetPdfToSign(userfilePath);

                // Recover the interface for the cloud certificate to be passed to PadesSigner class.
                var certificatesWithKey = await completeAuthResult.GetCertificatesWithKeyAsync();

                signingCertificate = certificatesWithKey.First();
                signer.SetSigningCertificate(signingCertificate);

                // Set a visual representation for the signature.
                signer.SetVisualRepresentation(PadesVisualElements.GetVisualRepresentationForPkiSdk(signingCertificate.Certificate));

                // Call ComputeSignature(), which does all the work, including validation of the signer's certificate and of the resulting signature
                signer.ComputeSignature();

                // Get the signed PDF as an array of bytes
                signatureContent = signer.GetPadesSignature();
            } catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate
                // encoding cannot be read or if the certificate is expired.
                ModelState.AddModelError("", ex.ValidationResults.ToString());
                return(View());
            }

            return(View("SignatureInfo", new SignatureInfoModel()
            {
                // Store the signature file on the folder "App_Data/".
                // With this filename, it can show a link to download the signature file.
                File = StorageMock.Store(signatureContent, ".pdf"),
                SignerCertificate = signingCertificate.Certificate
            }));
        }
Example #13
0
        /**
         * This action is called after the form after the user press the button "Sign". This action will
         * receive the user's CPF and current password.
         */
        public async Task <ActionResult> Authorize(string userfile, string cpf, string service, string password)
        {
            byte[] signatureContent;
            PKCertificateWithKey signingCertificate;

            try {
                // Process CPF, removing all formatting.
                var plainCpf = Regex.Replace(cpf, "/[.-]/", "");

                // Get an instance of the TrustServiceManager class, responsible for communicating with PSCs
                // and handling the OAuth flow.
                var manager = Util.GetTrustServicesManager();

                // Complete authentication using CPF and current password. The following method has three
                // sessionTypes:
                // - SINGLE_SIGNATURE: The returned token can only be used for one single signature request.
                // - MULTI_SIGNATURE: The returned token can only be used for one multi signature request.
                // - SIGNATURE_SESSION: The return token can only be used for one or more signature requests.
                var passwordAuthorizeResult = await manager.PasswordAuthorizeAsync(service, plainCpf, password, TrustServiceSessionTypes.SignatureSession);

                // Verify if the userfile exists and get its absolute path.
                string userfilePath;
                if (!StorageMock.TryGetFile(userfile, out userfilePath))
                {
                    return(HttpNotFound());
                }

                // Get an instance of the PadesSigner class, responsible for receiving the signature elements
                // and performing the local signature.
                var signer = new PadesSigner();

                // Set signature policy.
                signer.SetPolicy(GetSignaturePolicy());

                // Set file to be signed.
                signer.SetPdfToSign(userfilePath);

                // Recover the interface for the cloud certificate to be passed to PadesSigner class.
                var certificatesWithKey = await passwordAuthorizeResult.GetCertificatesWithKeyAsync();

                signingCertificate = certificatesWithKey.First();
                signer.SetSigningCertificate(signingCertificate);

                // Set a visual representation for the signature.
                signer.SetVisualRepresentation(PadesVisualElements.GetVisualRepresentationForPkiSdk(signingCertificate.Certificate));

                // Call ComputeSignature(), which does all the work, including validation of the signer's certificate and of the resulting signature
                signer.ComputeSignature();

                // Get the signed PDF as an array of bytes
                signatureContent = signer.GetPadesSignature();
            } catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate
                // encoding cannot be read or if the certificate is expired.
                ModelState.AddModelError("", ex.ValidationResults.ToString());
                return(View());
            }

            return(View("SignatureInfo", new SignatureInfoModel()
            {
                // Store the signature file on the folder "App_Data/".
                // With this filename, it can show a link to download the signature file.
                File = StorageMock.Store(signatureContent, ".pdf"),
                SignerCertificate = signingCertificate.Certificate
            }));
        }