public ActionResult Start(BatchSignatureStartRequest request) { // Instantiate a CadesSigner class var cadesSigner = new CadesSigner(); // Get the file's content. if (!StorageMock.TryGetFile(StorageMock.GetBatchDocPath(request.Id), out byte[] fileContent))
// GET: CadesServerKeySdk public ActionResult Index(string userfile) { byte[] signatureContent; PKCertificateWithKey certWithKey; try { // Instantiate a CadesSigner class var cadesSigner = new CadesSigner(); // Verify if the userfile exists and get the content of the userfile. if (!StorageMock.TryGetFile(userfile, out byte[] userfileContent))
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 Start(SignatureStartRequest request) { byte[] toSignBytes; SignatureAlgorithm signatureAlg; try { // Decode the user's certificate var cert = PKCertificate.Decode(request.Certificate); // Instantiate a CadesSigner class var cadesSigner = new CadesSigner(); // Set the data to sign, which in the case of this example is a fixed sample document if (!string.IsNullOrEmpty(request.FileId)) { cadesSigner.SetDataToSign(Storage.GetFile(request.FileId)); } else { cadesSigner.SetDataToSign(Storage.GetSampleDocContent()); } // Set the signer certificate cadesSigner.SetSigningCertificate(cert); // Set the signature policy cadesSigner.SetPolicy(getSignaturePolicy()); // Generate the "to-sign-bytes". This method also yields the signature algorithm that must // be used on the client-side, based on the signature policy. toSignBytes = cadesSigner.GenerateToSignBytes(out signatureAlg); } 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. return(new ResponseMessageResult(Request.CreateResponse(HttpStatusCode.BadRequest, new ValidationErrorModel(ex.ValidationResults)))); } // Create response with some informations that we'll use on Complete action and on client-side. var response = new SignatureStartResponse() { // Send to the javascript the "to sign hash" of the document and the digest algorithm that must // be used on the signature algorithm computation ToSignBytes = toSignBytes, DigestAlgorithmOid = signatureAlg.DigestAlgorithm.Oid }; return(Ok(response)); }
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 Index(SignatureStartModel model) { byte[] toSignBytes; SignatureAlgorithm signatureAlg; try { // Instantiate a CadesSigner class var cadesSigner = new CadesSigner(); // Set the data to sign, which in the case of this example is a fixed sample document cadesSigner.SetDataToSign(Storage.GetSampleDocContent()); // Decode the user's certificate and set as the signer certificate cadesSigner.SetSigningCertificate(PKCertificate.Decode(model.CertContent)); // Set the signature policy cadesSigner.SetPolicy(getSignaturePolicy()); // Generate the "to-sign-bytes". This method also yields the signature algorithm that must // be used on the client-side, based on the signature policy. toSignBytes = cadesSigner.GenerateToSignBytes(out signatureAlg); } 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()); } // On the next step (Complete action), we'll need once again some information: // - The content of the selected certificate used to validate the signature in complete action. // - The thumbprint of the selected certificate. // - The "to-sign-bytes" used to validate the signature in complete action. // - The "to-sign-hash" (digest of the "to-sign-bytes") to be signed. (see signature-complete-form.js) // - The OID of the digest algorithm to be used during the signature operation. // We'll store these values on TempData, which is a dictionary shared between actions. TempData["SignatureCompleteModel"] = new SignatureCompleteModel() { CertContent = model.CertContent, CertThumb = model.CertThumb, ToSignBytes = toSignBytes, ToSignHash = signatureAlg.DigestAlgorithm.ComputeHash(toSignBytes), DigestAlgorithmOid = signatureAlg.DigestAlgorithm.Oid }; return(RedirectToAction("Complete")); }
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")); }
protected void SubmitCertificateButton_Click(object sender, EventArgs e) { byte[] toSignBytes; SignatureAlgorithm signatureAlg; try { // Decode the user's certificate. var cert = PKCertificate.Decode(Convert.FromBase64String(CertificateField.Value)); // Instantiate a CadesSigner class. var cadesSigner = new CadesSigner(); // Set the data to sign, which in the case of this example is a fixed sample document. cadesSigner.SetDataToSign(Storage.GetSampleDocContent()); // Set the signer certificate. cadesSigner.SetSigningCertificate(cert); // Set the signature policy. cadesSigner.SetPolicy(getSignaturePolicy()); // Generate the "to-sign-bytes". This method also yields the signature algorithm that must be // used on the client-side, based on the signature policy. toSignBytes = cadesSigner.GenerateToSignBytes(out signatureAlg); } 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. ex.ValidationResults.Errors.ForEach(ve => ModelState.AddModelError("", ve.ToString())); return; } // On the next step (SubmitSignatureButton_Click action), we'll need once again some information: // - The "to-sign-bytes" // - The "to-sign-hash" (digest of the "to-sign-bytes") // - The OID of the digest algorithm to be used during the signature operation // We'll set the hidden fields on this page, that'll be loaded again. ToSignBytesField.Value = Convert.ToBase64String(toSignBytes); ToSignHashField.Value = Convert.ToBase64String(signatureAlg.DigestAlgorithm.ComputeHash(toSignBytes)); DigestAlgorithmField.Value = signatureAlg.DigestAlgorithm.Oid; }
private static int RunSignAndReturnExitCode(SignOptions opts) { var certificates = WindowsCertificateStore.LoadPersonalCurrentUser().GetCertificatesWithKey().Where(c => c.Certificate.PkiBrazil.CPF != null).ToList(); var certificate = certificates[opts.Certificate]; var fileName = opts.InputFile; using var stream = File.OpenRead(fileName); var digestAlgorithm = DigestAlgorithm.SHA256; var digest = digestAlgorithm.ComputeHash(stream); var signer = new CadesSigner(); signer.SetSigningCertificate(certificate); signer.SetPolicy(CadesPoliciesForGeneration.GetPkiBrazilAdrBasica()); signer.SetEncapsulatedContent(false); signer.SetDataDigestToSign(digestAlgorithm, digest); signer.ComputeSignature(); var cades = signer.GetSignature(); File.WriteAllBytes(opts.SignedFile, cades); stream.Close(); return(0); }
public ActionResult Index(SignatureStartModel model) { byte[] toSignBytes; SignatureAlgorithm signatureAlg; try { // Instantiate a CadesSigner class var cadesSigner = new CadesSigner(); 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); } // Decode the user's certificate and set as the signer certificate. var cert = PKCertificate.Decode(model.CertContent); cadesSigner.SetSigningCertificate(cert); // Set the signature policy cadesSigner.SetPolicy(getSignaturePolicy()); // Generate the "to-sign-bytes". This method also yields the signature algorithm that must // be used on the client-side, based on the signature policy. toSignBytes = cadesSigner.GenerateToSignBytes(out signatureAlg); } 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()); } // On the next step (Complete action), we'll need once again some information: // - The content of the selected certificate used to validate the signature in complete action. // - The thumbprint of the selected certificate. // - The "to-sign-bytes" used to validate the signature in complete action. // - The "to-sign-hash" (digest of the "to-sign-bytes") to be signed. (see signature-complete-form.js) // - The OID of the digest algorithm to be used during the signature operation. // We'll store these values on TempData, which is a dictionary shared between actions. TempData["SignatureCompleteModel"] = new SignatureCompleteModel() { UserFile = model.UserFile, CmsFile = model.CmsFile, CertContent = model.CertContent, CertThumb = model.CertThumb, ToSignBytes = toSignBytes, ToSignHash = signatureAlg.DigestAlgorithm.ComputeHash(toSignBytes), DigestAlgorithmOid = signatureAlg.DigestAlgorithm.Oid }; return(RedirectToAction("Complete", new { userfile = model.UserFile, cmsfile = model.CmsFile })); }
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 }); }
public IHttpActionResult Start(SignatureStartRequest model) { byte[] toSign; SignatureAlgorithm signatureAlg; try { // Instantiate a CadesSigner class var cadesSigner = new CadesSigner(); // Set the data to sign, which in the case of this example is a fixed sample document cadesSigner.SetDataToSign(Util.GetSampleDocContent()); // Decode the user's certificate and set as the signer certificate cadesSigner.SetSigningCertificate(PKCertificate.Decode(model.Certificate)); // Set the signature policy cadesSigner.SetPolicy(getPolicy()); // Generate the "to-sign-bytes". This method also yields the signature algorithm that must // be used on the client-side, based on the signature policy. toSign = cadesSigner.GenerateToSignBytes(out signatureAlg); } 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. return Ok(new SignatureStartResponse() { Success = false, Message = "A validation error has occurred", ValidationResults = ex.ValidationResults.ToString() }); } // On the next step (Complete action), we'll need once again the signer's certificate and the // "to-sign-bytes" (besides from the document to be signed and the policy). We'll store these // values on the database and return to the page an identifier that will be later used to locate // these values again. SignatureProcess signatureProcess; using (var dbContext = new DbContext()) { signatureProcess = SignatureProcess.Create(); signatureProcess.CadesSignerCertificate = model.Certificate; signatureProcess.CadesToSign = toSign; dbContext.SignatureProcesses.Add(signatureProcess); dbContext.SaveChanges(); } // Send back to the page: // - The identifier that we'll later use to locate the user's certificate and "to-sign-bytes" // - The "to-sign-bytes" // - The OID of the digest algorithm to be used during the signature operation var response = new SignatureStartResponse() { Success = true, ProcessId = signatureProcess.Id, ToSign = toSign, DigestAlgorithmOid = signatureAlg.DigestAlgorithm.Oid }; return Ok(response); }
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(); }
private void startNextSignature() { // Increment the index of the document currently being signed. DocumentIndex += 1; // Check if we have reached the end of the batch, in which case we fill the hidden field // "ToSignHashField" with value "(end)", which signals to the javascript on batch-signature-form.js // that the process is completed and the page can be unblocked. if (DocumentIndex == DocumentIds.Count) { ToSignHashField.Value = "(end)"; return; } // Get the ID of the document currently being signed. var docId = DocumentIds[DocumentIndex]; byte[] toSignBytes; SignatureAlgorithm signatureAlg; try { // Decode the user's certificate. var cert = PKCertificate.Decode(Convert.FromBase64String(CertificateField.Value)); // Instantiate a CadesSigner class. var cadesSigner = new CadesSigner(); // Set the data to sign, which in the case of this example is a fixed sample document. cadesSigner.SetDataToSign(Storage.GetBatchDocContent(docId)); // Set the signer certificate. cadesSigner.SetSigningCertificate(cert); // Set the signature policy. cadesSigner.SetPolicy(getSignaturePolicy()); // Generate the "to-sign-bytes". This method also yields the signature algorithm that must be // used on the client-side, based on the signature policy. toSignBytes = cadesSigner.GenerateToSignBytes(out signatureAlg); } catch (ValidationException ex) { // One or more validations failed. We log the error, update the page with a summary of what // happened to this document and start the next signature. logger.Error(ex, "Validation error starting the signature of a batch document"); setValidationError(ex.ValidationResults); startNextSignature(); return; } catch (Exception ex) { // An error has occurred. We log the error, update the page with a summary of what happened to // this document and start the next signature. logger.Error(ex, "Error starting the signature of a batch document"); setError(ex.Message); startNextSignature(); return; } // Send to the javascript the "to sign hash" of the document (digest of the "to-sign-bytes") and the // digest algorithm that must be used on the signature algorithm computation. ToSignBytesField.Value = Convert.ToBase64String(toSignBytes); ToSignHashField.Value = Convert.ToBase64String(signatureAlg.DigestAlgorithm.ComputeHash(toSignBytes)); DigestAlgorithmField.Value = signatureAlg.DigestAlgorithm.Oid; }
private async Task <bool> sign(TaskProgressDialog progressDialog) { try { var signer = new CadesSigner(); if (CoSign) { progressDialog.Message = "Reading existing CAdES signature ..."; } else { progressDialog.Message = "Reading file ..."; } await Task.Delay(TimeSpan.FromMilliseconds(100)); if (CoSign) { var cmsBytes = await readAllBytesAsync(CmsPath, progressDialog.CancellationToken); signer.SetSignatureToCoSign(cmsBytes); } else { var fileBytes = await readAllBytesAsync(FilePath, progressDialog.CancellationToken); signer.SetDataToSign(fileBytes); } if (progressDialog.CancellationToken.IsCancellationRequested) { return(false); } progressDialog.Progress = 33; progressDialog.Message = "Signing ..."; await Task.Delay(TimeSpan.FromMilliseconds(100)); signer.SetSigningCertificate(SelectedCertificate.CertificateWithKey); signer.SetPolicy(CadesPoliciesForGeneration.GetCadesBasic(App.GetTrustArbitrator())); signer.SetEncapsulatedContent(this.EncapsulateContent); signer.ComputeSignature(); var signature = signer.GetSignature(); if (progressDialog.CancellationToken.IsCancellationRequested) { return(false); } progressDialog.Progress = 66; progressDialog.Message = "Saving signature ..."; await Task.Delay(TimeSpan.FromMilliseconds(100)); var saveFileDialog = new SaveFileDialog() { Filter = "CAdES signature files (.p7s)|*.p7s", FilterIndex = 1, FileName = CoSign ? string.Format("{0}-{1:yyyy-MM-dd-HHmmss}.p7s", Path.GetFileNameWithoutExtension(CmsPath), DateTime.Now) : FilePath + ".p7s" }; if (saveFileDialog.ShowDialog() != true) { return(false); } var outFilePath = saveFileDialog.FileName; await writeAllBytesAsync(outFilePath, signature, progressDialog.CancellationToken); if (progressDialog.CancellationToken.IsCancellationRequested) { return(false); } progressDialog.Progress = 100; progressDialog.Message = "Completed!"; return(true); } catch (ValidationException ex) { new ValidationResultsDialog("Validation failed", ex.ValidationResults).ShowDialog(); return(false); } catch (Exception ex) { logger.Error(ex, "Error while performing CAdES signature"); MessageBox.Show(ex.Message); return(false); } }