public async Task <IActionResult> Import([FromBody] CertificateImportRequest request)
        {
            // 1. Open PKCS#12, verifying valid of the provided password.
            Pkcs12CertificateStore store;

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

            // 2. Retrieve certification info.
            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();

            // Certificate infomation.
            var subjectName   = cert.Certificate.SubjectName.CommonName;
            var cpf           = cert.Certificate.PkiBrazil.CPF;
            var cpfFormatted  = cert.Certificate.PkiBrazil.CpfFormatted;
            var cnpj          = cert.Certificate.PkiBrazil.Cnpj;
            var cnpjFormatted = cert.Certificate.PkiBrazil.CnpjFormatted;
            var dateOfBirth   = cert.Certificate.PkiBrazil.DateOfBirth;

            // 3. Store certificate at Azure KeyVault.
            var certId = await _azureKeyVaultStore.ImportPkcs12Async(request.Pkcs12);

            // 4. Store certId in a database and associate it with the user account.
            // %%% EXAMPLE %%%
            //_businessService.Save(new User() {
            //	CertId = certId,
            //	Id = cpf,
            //});
            // %%%%%%%%%%%%%%%

            return(Ok(new CertificateImportResponse()
            {
                CertId = certId,
            }));
        }
        // GET: XmlServerKeySdk
        public ActionResult Index()
        {
            byte[] signatureContent;
            PKCertificateWithKey certWithKey;

            try {
                // Instantiate a XmlSigner class
                var signer = new FullXmlSigner();

                // Set the data to sign, which in the case of this example is a fixed sample document
                signer.SetXml(StorageMock.GetSampleXmlDocumentContent());


                // Get the server's certificate, stores it and and set as the signer certificate.
                var certContent = StorageMock.GetServerCertificate();
                var store       = Pkcs12CertificateStore.Load(certContent, "1234");
                certWithKey = store.GetCertificatesWithKey().First();
                signer.SetSigningCertificate(certWithKey);

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

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

                // Get the signed XML as an array of bytes
                signatureContent = signer.GetSignedXml();
            } 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(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 = certWithKey.Certificate
            }));
        }
Example #3
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,
            }));
        }