Esempio n. 1
0
        protected void SubmitSignatureButton_Click(object sender, EventArgs e)
        {
            PKCertificate cert;

            byte[] signatureContent;

            try {
                // Decode the user's certificate.
                cert = PKCertificate.Decode(Convert.FromBase64String(CertificateField.Value));

                // Instantiate a CadesSigner class.
                var cadesSigner = new CadesSigner();

                // Set the document to be signed and the policy, exactly like in the previous action
                // (SubmitCertificateButton_Click).
                cadesSigner.SetDataToSign(Storage.GetSampleDocContent());
                cadesSigner.SetPolicy(getSignaturePolicy());

                // Set the signer certificate.
                cadesSigner.SetSigningCertificate(cert);

                // Set the signature computed on the client-side, along with the "to-sign-bytes" recovered from
                // the page.
                cadesSigner.SetPrecomputedSignature(Convert.FromBase64String(SignatureField.Value), Convert.FromBase64String(ToSignBytesField.Value));

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

                // Get the signature as an array of bytes.
                signatureContent = cadesSigner.GetSignature();
            }
            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 CadesSignatureInfo 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, ".p7s");
            this.Certificate   = cert;

            Server.Transfer("CadesSignatureInfo.aspx");
        }
        public IHttpActionResult Complete(SignatureCompleteRequest request)
        {
            byte[] signatureContent;

            try {
                // Instantiate a CadesSigner class
                var cadesSigner = new CadesSigner();

                // Set the document to be signed and the policy, exactly like in the Start action
                if (!string.IsNullOrEmpty(request.FileId))
                {
                    cadesSigner.SetDataToSign(Storage.GetFile(request.FileId));
                }
                else
                {
                    cadesSigner.SetDataToSign(Storage.GetSampleDocContent());
                }

                cadesSigner.SetPolicy(getSignaturePolicy());

                // Set signer's certificate
                cadesSigner.SetSigningCertificate(PKCertificate.Decode(request.Certificate));

                // Set the signature computed on the client-side, along with the "to-sign-bytes" received from the request.
                cadesSigner.SetPrecomputedSignature(request.Signature, request.ToSignBytes);

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

                // Get the signature as an array of bytes
                signatureContent = cadesSigner.GetSignature();
            } 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, ".p7s"),
                Certificate = new CertificateModel(PKCertificate.Decode(request.Certificate))
            };

            return(Ok(response));
        }
        public ActionResult Complete(SignatureCompleteModel model)
        {
            byte[] signatureContent;

            try {
                // Instantiate a CadesSigner class
                var cadesSigner = new CadesSigner();

                // Set the document to be signed and the policy, exactly like in the Start method
                cadesSigner.SetDataToSign(Storage.GetSampleDocContent());
                cadesSigner.SetPolicy(getSignaturePolicy());

                // Set signer's certificate
                cadesSigner.SetSigningCertificate(PKCertificate.Decode(model.CertContent));

                // Set the signature computed on the client-side, along with the "to-sign-bytes" (rendered in a hidden input field, see the view)
                cadesSigner.SetPrecomputedSignature(model.Signature, model.ToSignBytes);

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

                // Get the signature as an array of bytes
                signatureContent = cadesSigner.GetSignature();
            } 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, ".p7s"),
                UserCert = PKCertificate.Decode(model.CertContent)
            };

            return(RedirectToAction("SignatureInfo"));
        }
Esempio n. 4
0
        public ActionResult Complete(SignatureCompleteModel model)
        {
            byte[] signatureContent;

            try {
                // Instantiate a CadesSigner class
                var cadesSigner = new CadesSigner();

                // Set the document to be signed, exactly like in the Start method
                if (!string.IsNullOrEmpty(model.CmsFile))
                {
                    // Verify if the cmsfile exists and get the content of the cmsfile.
                    byte[] cmsfileContent;
                    if (!StorageMock.TryGetFile(model.CmsFile, out cmsfileContent))
                    {
                        return(HttpNotFound());
                    }

                    // If the URL argument "cmsfile" is filled, the user has asked to co-sign a previously signed
                    // CMS. We'll set the path to the CMS to be co-signed, which was perviously saved in the
                    // App_Data folder by the POST action on this controller.
                    cadesSigner.SetSignatureToCoSign(cmsfileContent);
                }
                else
                {
                    // Verify if the userfile exists and get the content of the userfile.
                    byte[] userfileContent;
                    if (!StorageMock.TryGetFile(model.UserFile, out userfileContent))
                    {
                        return(HttpNotFound());
                    }

                    // If the URL argument "userfile" is filled, it means the user was redirected here by
                    // UploadController (signature with file uploaded by user). We'll set the path of the file to
                    // be signed, which was saved in the App_Data folder by UploadController.
                    cadesSigner.SetDataToSign(userfileContent);
                }

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

                // Decode the user's certificate and set as the signer certificate.
                var cert = PKCertificate.Decode(model.CertContent);
                cadesSigner.SetSigningCertificate(cert);

                // Set the signature computed on the client-side, along with the "to-sign-bytes" (rendered in a hidden input field, see the view)
                cadesSigner.SetPrecomputedSignature(model.Signature, model.ToSignBytes);

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

                // Get the signature as an array of bytes
                signatureContent = cadesSigner.GetSignature();
            } 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("Complete", model));
            }

            // On the next step (SignatureInfo action), we'll render the following information:]
            // - The filename to be available to download in next action.
            // 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, ".p7s")
            };

            return(RedirectToAction("SignatureInfo"));
        }
        public IHttpActionResult Complete(SignatureCompleteRequest model)
        {
            // We'll use the SignatureProcess ID to locate the values we stored during the signature first step
            SignatureProcess signatureProcess;
            using (var dbContext = new DbContext()) {
                signatureProcess = dbContext.SignatureProcesses.FirstOrDefault(p => p.Id == model.ProcessId);
                // We won't be needing this information again, so let's do some housekeeping
                if (signatureProcess != null) {
                    dbContext.SignatureProcesses.Remove(signatureProcess);
                    dbContext.SaveChanges();
                }
            }

            // If we haven't found the SignatureProcess, something went wrong and we cannot continue (this shouldn't normally happen)
            if (signatureProcess == null) {
                return NotFound();
            }

            byte[] signatureContent;
            try {

                var cadesSigner = new CadesSigner();

                // Set the document to be signed and the policy, exactly like in the Start method
                cadesSigner.SetDataToSign(Util.GetSampleDocContent());
                cadesSigner.SetPolicy(getPolicy());

                // Set signer's certificate recovered from the database
                cadesSigner.SetSigningCertificate(PKCertificate.Decode(signatureProcess.CadesSignerCertificate));

                // Set the signature computed on the client-side, along with the "to-sign-bytes" recovered from the database
                cadesSigner.SetPrecomputedSignature(model.Signature, signatureProcess.CadesToSign);

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

                // Get the signature as an array of bytes
                signatureContent = cadesSigner.GetSignature();

            } catch (ValidationException ex) {
                // Some of the operations above may throw a ValidationException, for instance if the certificate is revoked.
                return Ok(new SignatureCompleteResponse() {
                    Success = false,
                    Message = "A validation error has occurred",
                    ValidationResults = ex.ValidationResults.ToString()
                });
            }

            // Store the signature for future download (see method SignatureController.Download in the Controllers folder)
            Signature signature;
            using (var dbContext = new DbContext()) {
                signature = Signature.Create();
                signature.Type = SignatureTypes.Cades;
                signature.Content = signatureContent;
                dbContext.Signatures.Add(signature);
                dbContext.SaveChanges();
            }

            // Inform the page of the success, along with the ID of the stored signature, so that the page
            // can render the download link
            return Ok(new SignatureCompleteResponse() {
                Success = true,
                SignatureId = signature.Id
            });
        }
Esempio n. 6
0
        private void completeSignature()
        {
            // Get the ID of the document currently being signed.
            var docId = DocumentIds[DocumentIndex];

            PKCertificate cert;

            byte[] signatureContent;

            try {
                // Decode the user's certificate.
                cert = PKCertificate.Decode(Convert.FromBase64String(CertificateField.Value));

                // Instantiate a CadesSigner class.
                var cadesSigner = new CadesSigner();

                // Set the document to be signed and the policy, exactly like in the previous action
                // (SubmitCertificateButton_Click).
                cadesSigner.SetDataToSign(Storage.GetBatchDocContent(docId));
                cadesSigner.SetPolicy(getSignaturePolicy());

                // Set the signer certificate.
                cadesSigner.SetSigningCertificate(cert);

                // Optionally, set whether the content should be encapsulated in the resulting CMS.
                cadesSigner.SetEncapsulatedContent(false);

                // Set the signature computed on the client-side, along with the "to-sign-bytes" recovered from
                // the page.
                cadesSigner.SetPrecomputedSignature(Convert.FromBase64String(SignatureField.Value), Convert.FromBase64String(ToSignBytesField.Value));

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

                // Get the signature as an array of bytes.
                signatureContent = cadesSigner.GetSignature();
            }
            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, ".p7s");

            // 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();
        }