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))
        public ActionResult Start(BatchSignatureStartRequest request)
        {
            byte[]             toSignBytes, transferData;
            SignatureAlgorithm signatureAlg;

            try {
                // Decode the user's certificate
                var cert = PKCertificate.Decode(request.CertContent);

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

                // Set the PDF to sign, which in the case of this example is one of the batch documents
                padesSigner.SetPdfToSign(StorageMock.GetBatchDocPath(request.Id));

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

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

                // Set a visual representation for the signature.
                padesSigner.SetVisualRepresentation(PadesVisualElements.GetVisualRepresentationForPkiSdk(cert));

                // 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, as well as the "transfer data",
                // a byte-array that will be needed on the next step.
                toSignBytes = padesSigner.GetToSignBytes(out signatureAlg, out transferData);
            } 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 HttpStatusCodeResult(500, ex.ValidationResults.ToString()));
            }

            // For the next steps, we'll need once again some information:
            // - The "transfer data" filename. Its content is stored in a temporary file (with extension .bin) to
            // be shared with the Complete action.
            // - The "to-sign-hash" (digest of the "to-sign-bytes"). And the OID of the digest algorithm to be
            // used during the signature operation. this information is need in the signature computation with
            // Web PKI component. (see batch-signature-form.js)
            return(Json(new BatchSignatureStartResponse()
            {
                TransferDataFileId = StorageMock.Store(transferData, ".bin"),
                ToSignHash = signatureAlg.DigestAlgorithm.ComputeHash(toSignBytes),
                DigestAlgorithmOid = signatureAlg.DigestAlgorithm.Oid
            }));
        }
        public ActionResult Start(BatchSignatureStartRequest request)
        {
            // Recover the batch information based on its ID, which contains the user's certificate
            var batchInfo = batches[request.BatchId];

            // Get an instance of the PadesSignatureStarter class, responsible for receiving the signature elements and start the
            // signature process
            var signatureStarter = new PadesSignatureStarter(Util.GetRestPkiClient())
            {
                // Set the user's certificate. Notice that this step is not necessary on the regular batch signature example. This
                // enhances the performance of the batch processing
                SignerCertificate = Convert.FromBase64String(batchInfo.Certificate),

                // Set the signature policy
                SignaturePolicyId = StandardPadesSignaturePolicies.Basic,

                // Set a SecurityContext to be used to determine trust in the certificate chain
                SecurityContextId = StandardSecurityContexts.PkiBrazil,
                // Note: By changing the SecurityContext above you can accept certificates from a custom security context created on the Rest PKI website.

                // Set a visual representation for the signature
                VisualRepresentation = new PadesVisualRepresentation()
                {
                    // The tags {{signerName}} and {{signerNationalId}} will be substituted according to the user's certificate
                    // signerName -> full name of the signer
                    // signerNationalId -> if the certificate is ICP-Brasil, contains the signer's CPF
                    Text = new PadesVisualText("Signed by {{signerName}} ({{signerNationalId}})")
                    {
                        // Specify that the signing time should also be rendered
                        IncludeSigningTime = true,

                        // Optionally set the horizontal alignment of the text ('Left' or 'Right'), if not set the default is Left
                        HorizontalAlign = PadesTextHorizontalAlign.Left
                    },

                    // We'll use as background the image in Content/PdfStamp.png
                    Image = new PadesVisualImage(Util.GetPdfStampContent(), "image/png")
                    {
                        // Opacity is an integer from 0 to 100 (0 is completely transparent, 100 is completely opaque).
                        Opacity = 50,

                        // Align the image to the right
                        HorizontalAlign = PadesHorizontalAlign.Right
                    },

                    // Position of the visual representation. We have encapsulated this code in a method to include several
                    // possibilities depending on the argument passed. Experiment changing the argument to see different examples
                    // of signature positioning. Once you decide which is best for your case, you can place the code directly here.
                    Position = getVisualPositioning(1)
                }
            };

            // Set the document to be signed based on its ID (passed to us from the page)
            signatureStarter.SetPdfToSign(Util.GetBatchDocContent(request.DocumentId));

            // Call the Start() method, which initiates the signature. Notice that, on the regular signature example, we call the
            // StartWithRestPki() method, which is simpler but with worse performance. The Start() method will yield not only the
            // token, a 43-character case-sensitive URL-safe string which identifies this signature process, but also the data
            // that should be used to call the signHash() function on the Web PKI component (instead of the signWithRestPki()
            // function, which is also simpler but far slower).
            var signatureParams = signatureStarter.Start();

            // Notice: it is not necessary to call SetNoCacheHeaders() because this action is a POST action, therefore no caching
            // of the response will be made by browsers.

            // Return a JSON with the token obtained from REST PKI, along with the parameters for the signHash() call
            // (the page will use jQuery to decode this value)
            var response = new BatchSignatureStartResponse()
            {
                Token              = signatureParams.Token,
                ToSignHash         = Convert.ToBase64String(signatureParams.ToSignHash),
                DigestAlgorithmOid = signatureParams.DigestAlgorithmOid
            };

            return(Json(response));
        }
示例#4
0
        public IHttpActionResult Start(BatchSignatureStartRequest request)
        {
            byte[]             toSignBytes, transferData;
            SignatureAlgorithm signatureAlg;

            try {
                // Decode the user's certificate
                var cert = PKCertificate.Decode(request.CertContent);

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

                // Set the PDF to sign, which in the case of this example is one of the batch documents
                padesSigner.SetPdfToSign(Storage.GetBatchDocContent(request.Id));

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

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

                // Set the signature's visual representation options (this is optional). For more information, see
                // http://pki.lacunasoftware.com/Help/html/98095ec7-2742-4d1f-9709-681c684eb13b.htm
                var visual = new PadesVisualRepresentation2()
                {
                    // Text of the visual representation
                    Text = new PadesVisualText()
                    {
                        // Compose the message
                        CustomText = $"Assinado digitalmente por {cert.SubjectDisplayName}",

                        // Specify that the signing time should also be rendered
                        IncludeSigningTime = true,

                        // Optionally set the horizontal alignment of the text ('Left' or 'Right'), if not set the default is Left
                        HorizontalAlign = PadesTextHorizontalAlign.Left
                    },
                    // Background image of the visual representation
                    Image = new PadesVisualImage()
                    {
                        // We'll use as background the image in Content/PdfStamp.png
                        Content = Storage.GetPdfStampContent(),

                        // Opacity is an integer from 0 to 100 (0 is completely transparent, 100 is completely opaque).
                        Opacity = 50,

                        // Align the image to the right
                        HorizontalAlign = PadesHorizontalAlign.Right
                    },
                    // Set the position of the visual representation
                    Position = PadesVisualAutoPositioning.GetFootnote()
                };
                padesSigner.SetVisualRepresentation(visual);

                // 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, as well as the "transfer data",
                // a byte-array that will be needed on the next step.
                toSignBytes = padesSigner.GetToSignBytes(out signatureAlg, out transferData);
            } 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.
                var message = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ValidationResults.ToString());
                return(ResponseMessage(message));
            }

            // For the next steps, we'll need once again some information:
            // - The "transfer data" filename. Its content is stored in a temporary file (with extension .bin) to
            // be shared with the Complete action.
            // - The "to-sign-hash" (digest of the "to-sign-bytes"). And the OID of the digest algorithm to be
            // used during the signature operation. this information is need in the signature computation with
            // Web PKI component. (see batch-signature-form.js)
            return(Ok(new BatchSignatureStartResponse()
            {
                TransferDataFileId = Storage.StoreFile(transferData, ".bin"),
                ToSignHash = signatureAlg.DigestAlgorithm.ComputeHash(toSignBytes),
                DigestAlgorithmOid = signatureAlg.DigestAlgorithm.Oid
            }));
        }