Example #1
0
    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);
    }
Example #2
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();
        }
Example #3
0
        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);
            }
        }