public void SignXml_ShouldSignXmlStringWithPrivateKeyCertificate()
        {
            var input = new SignXmlInput
            {
                CertificatePath    = _certificatePath,
                PrivateKeyPassword = _privateKeyPassword,
                SigningStrategy    = SigningStrategyType.PrivateKeyCertificate,
                XmlInputType       = XmlParamType.XmlString,
                XmlEnvelopingType  = XmlEnvelopingType.XmlEnvelopedSignature,
                Xml = "<root><value>foo</value></root>"
            };
            var output = new SignXmlOutput
            {
                OutputType = XmlParamType.XmlString
            };
            var options = new SignXmlOptions
            {
                DigestMethod       = DigestMethod.SHA256,
                TransformMethods   = new [] { TransformMethod.DsigExcC14 },
                XmlSignatureMethod = XmlSignatureMethod.RSASHA256
            };

            SigningResult result = SigningTask.SignXml(input, output, options);

            StringAssert.Contains("<Signature", result.Result);
        }
Example #2
0
        internal void Retry(SigningResult result)
        {
            Result     = SigningResult.Pending;
            Passphrase = null;
            IsApproved = false;
            taskUser   = new SyncEvent();

            var attempt = taskSign;

            taskSign = new SyncEvent <SigningResult>();

            attempt.SetComplete(result);
        }
Example #3
0
        protected virtual KeyValuePair <IPdfSigningSession, ISigningResult> SignDocumentInternal(ISigningRequest signRequest)
        {
            var result      = new SigningResult();
            var sessionData = Cache.Get(signRequest.FileId) as IPdfSigningSession;

            if (sessionData == default(IPdfSigningSession))
            {
                result = new SigningResult
                {
                    FileId    = signRequest.FileId,
                    Exception = new TimeoutException()
                };
            }
            else
            {
                try
                {
                    PdfSignerService
                    .SignData(sessionData, signRequest.SignedHashBase64);

                    result = new SigningResult
                    {
                        FileId    = signRequest.FileId,
                        Exception = default(Exception)
                    };

                    OnDocumentSigned(sessionData);
                }
                catch (Exception ex)
                {
                    result = new SigningResult
                    {
                        FileId    = signRequest.FileId,
                        Exception = ex
                    };

                    OnDocumentError(sessionData, signRequest.Parameters, ex);
                }
            }

            sessionData = Cache.Get(signRequest.FileId) as IPdfSigningSession;
            return(new KeyValuePair <IPdfSigningSession, ISigningResult>(sessionData, result));
        }
Example #4
0
        public async Task Approval_Cancel()
        {
            Approval      approval = null;
            SigningResult result   = SigningResult.Pending;

            Engine.ApprovalRequired += async a =>
            {
                approval = a;
                result   = await a.Approve(false);

                Assert.IsFalse(a.IsApproved);
            };

            var task = await Engine.CreateAccount("Account", manager, manager, 100);

            Assert.IsNull(approval.LastError);
            Assert.IsFalse(approval.IsApproved);
            Assert.AreEqual(SigningResult.Cancelled, result);
        }
        public void SignXml_ShouldSignXmlFileWithPrivateKeyCertificate()
        {
            // create file
            string xmlFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestItems", Guid.NewGuid().ToString() + ".xml");

            File.WriteAllText(xmlFilePath, @"<root>
    <value>foo</value>
</root>");
            var input = new SignXmlInput
            {
                CertificatePath    = _certificatePath,
                PrivateKeyPassword = _privateKeyPassword,
                SigningStrategy    = SigningStrategyType.PrivateKeyCertificate,
                XmlEnvelopingType  = XmlEnvelopingType.XmlEnvelopedSignature,
                XmlInputType       = XmlParamType.File,
                XmlFilePath        = xmlFilePath
            };
            var output = new SignXmlOutput
            {
                OutputType     = XmlParamType.File,
                OutputFilePath = xmlFilePath.Replace(".xml", "_signed.xml"),
                OutputEncoding = "utf-8"
            };
            var options = new SignXmlOptions
            {
                DigestMethod       = DigestMethod.SHA256,
                TransformMethods   = new [] { TransformMethod.DsigExcC14 },
                XmlSignatureMethod = XmlSignatureMethod.RSASHA256,
                PreserveWhitespace = true
            };

            SigningResult result    = SigningTask.SignXml(input, output, options);
            var           signedXml = File.ReadAllText(result.Result);

            StringAssert.Contains("<Signature", signedXml);
            StringAssert.DoesNotContain("<Signature", File.ReadAllText(xmlFilePath));

            // cleanup
            File.Delete(xmlFilePath);
            File.Delete(result.Result);
        }
Example #6
0
        public async Task Approval_PasswordFailure()
        {
            Approval      approval = null;
            SigningResult result   = SigningResult.Pending;

            Engine.ApprovalRequired += async a =>
            {
                approval = a;

                a.PassphraseText = Wrong;

                result = await a.Approve(true);

                Assert.AreEqual(SigningResult.InvalidCredentials, result);
                Assert.AreEqual(SigningResult.Pending, approval.Result);

                result = await a.Approve(false);
            };

            var task = await Engine.CreateAccount("Account", manager, manager, 100);

            Assert.AreEqual(SigningResult.Cancelled, result);
        }
Example #7
0
        public async Task Approval_Process()
        {
            Approval      approval = null;
            SigningResult result   = SigningResult.Pending;

            Engine.ApprovalRequired += async a =>
            {
                approval = a;
                Assert.IsFalse(a.IsApproved);

                a.PassphraseText = Right;
                result           = await a.Approve(true);

                Assert.IsTrue(a.IsApproved);
            };

            var task = await Engine.CreateAccount("Account", manager, manager, 100);

            Assert.IsNotNull(approval);
            Assert.AreSame(manager, approval.Signer);
            Assert.IsNull(approval.LastError);
            Assert.IsTrue(approval.IsApproved);
            Assert.AreEqual(SigningResult.Signed, result);
        }
Example #8
0
        protected virtual IEnumerable <ISigningResult> GetDocumentsAuthenticatedAttributesInternal(
            bool async,
            string[] filesIds,
            string userId,
            string userCertificateBase64,
            string location,
            string reason,
            string hashAlgorithm,
            string signatureAlgorithm,
            IDictionary <string, object> parameters = default(IDictionary <string, object>),
            int timeoutInSeconds = default(int)
            )
        {
            if (parameters == default(IDictionary <string, object>))
            {
                parameters = new Dictionary <string, object> {
                };
            }

            var results         = new List <ISigningResult>();
            var userCertificate = userCertificateBase64
                                  .ToX509Certificate2();
            var ownerIdentification = OidHelper
                                      .OwnerIdentificationWorkflow
                                      .Execute(userCertificate);

            results
            .AddRange(OnValidateUserCertificate(filesIds, userCertificate));

            if (!results.Any()) //não houve erros de certificado
            {
                var documents = GetDocuments <ISigningDocument>(filesIds, userId, parameters);

                var unauthorizedDocuments = filesIds
                                            .Where(o => !documents.Any(p => p.FileId == o));

                foreach (var fileId in unauthorizedDocuments)
                {
                    var result = new SigningResult
                    {
                        FileId    = fileId,
                        Exception = new UnauthorizedAccessException("You do not have permission to access this file")
                    };

                    var document = new SigningDocument
                    {
                        FileId     = result.FileId,
                        Parameters = parameters,
                        UserId     = userId
                    };

                    results
                    .Add(result);
                    OnDocumentError(document, parameters, result.Exception);
                }

                if (async)
                {
                    var list = new ConcurrentBag <ISigningResult>();

                    Parallel
                    .ForEach(documents, document =>
                    {
                        var result = GetDocumentAuthenticatedAttributesInternal
                                     (
                            document,
                            ownerIdentification,
                            location,
                            reason,
                            hashAlgorithm,
                            signatureAlgorithm,
                            userCertificate,
                            parameters,
                            timeoutInSeconds
                                     );

                        list
                        .Add(result);
                    });

                    results
                    .AddRange(list);
                }
                else
                {
                    foreach (var document in documents)
                    {
                        var result = GetDocumentAuthenticatedAttributesInternal
                                     (
                            document,
                            ownerIdentification,
                            location,
                            reason,
                            hashAlgorithm,
                            signatureAlgorithm,
                            userCertificate,
                            parameters,
                            timeoutInSeconds
                                     );

                        results
                        .Add(result);
                    }
                }
            }

            return(results);
        }
Example #9
0
        protected virtual ISigningResult GetDocumentAuthenticatedAttributesInternal
        (
            ISigningDocument document,
            string ownerIdentification,
            string location,
            string reason,
            string hashAlgorithm,
            string signatureAlgorithm,
            X509Certificate2 userCertificate,
            IDictionary <string, object> parameters = default(IDictionary <string, object>),
            int timeoutInSeconds = default(int)
        )
        {
            var removeCache = false;
            var result      = default(ISigningResult);

            try
            {
                var pdfSigningSession = new PdfSigningSession
                {
                    FileId              = document.FileId,
                    UserId              = document.UserId,
                    FilePath            = document.FilePath,
                    HashAlgorithm       = hashAlgorithm,
                    OwnerIdentification = ownerIdentification,
                    SignatureAlgorithm  = signatureAlgorithm,
                    SignatureVisible    = true,
                    UserCertificate     = userCertificate,
                    Location            = location,
                    Reason              = reason,
                    Parameters          = parameters
                };

                if (timeoutInSeconds == default(int))
                {
                    timeoutInSeconds = CacheTimeoutInSeconds;
                }

                var cachePolicy = GetCacheItemPolicy(timeoutInSeconds);
                OnCreateCache(pdfSigningSession, pdfSigningSession, cachePolicy, out removeCache);

                //necessário criar o documento somente depois que o cache foi criado
                //para evitar exceção por utilização simultânea do documento temporário
                CopyFileToTemporaryFilePath(pdfSigningSession);
                UpdateDocument(pdfSigningSession, document);

                pdfSigningSession.AuthenticatedAttributes = PdfSignerService
                                                            .CreateAuthenticatedAttribute(pdfSigningSession);

                result = new SigningResult
                {
                    FileId = document.FileId,
                    AuthenticatedAttributeBase64 = pdfSigningSession.AuthenticatedAttributes.ValueBase64,
                    Exception = default(Exception)
                };
            }
            catch (Exception ex)
            {
                result = new SigningResult
                {
                    FileId = document.FileId,
                    AuthenticatedAttributeBase64 = default(string),
                    Exception = ex
                };

                if (removeCache)
                {
                    Cache
                    .Remove(document.FileId);
                }

                OnDocumentError(document, parameters, ex);
            }

            return(result);
        }
Example #10
0
 internal void Close(SigningResult result)
 {
     Result = result;
     taskSign.SetComplete(result);
 }