Example #1
0
        public async Task SignAsync(SignTask task, SignOptions signOptions)
        {
            var SignClien = new RestClient("https://mobilelearn.chaoxing.com/pptSign/stuSignajax")
            {
                CookieContainer = _Cookie
            };
            var request = new RestRequest(Method.GET);

            // ?activeId=292002019&appType=15&ifTiJiao=1&latitude=-1&longitude=-1&clientip=1.1.1.1&address=中国&objectId=3194679e88dbc9c60a4c6e31da7fa905
            request.AddParameter("activeId", task.Id);
            request.AddParameter("appType", "15");
            request.AddParameter("ifTiJiao", "1");
            request.AddParameter("latitude", signOptions.Latitude);
            request.AddParameter("longitude", signOptions.Longitude);
            request.AddParameter("clientip", signOptions.ClientIp);
            request.AddParameter("address", signOptions.Address);
            request.AddParameter("objectId", signOptions.ImageId);
            var response = await SignClien.ExecuteGetAsync(request);

            if (response.Content == "success" || response.Content == "您已签到过了")
            {
                return;
            }
            throw new Exception($"签到出错: {response.Content}");
        }
Example #2
0
        public Stream CreateFile(FileDescription fileDescription, SignOptions signOptions = null,
                                 SaveOptions saveOptions = null)
        {
            CloudBlobContainer container = GetContainerReference();
            string             name      = fileDescription.GUID.ToLower();
            CloudBlockBlob     blob      = container.GetBlockBlobReference(name);

            using (MemoryStream emptyStream = new MemoryStream())
            {
                blob.UploadFromStream(emptyStream);
            }

            try
            {
                CloudAppendBlob appendBlob = container.GetAppendBlobReference(name);
                appendBlob.CreateOrReplace();
                return(appendBlob.OpenWrite(true));
            }
            catch (Microsoft.WindowsAzure.Storage.StorageException exception)
            {
                // Azure Storage Emulator does not support append BLOBs,
                // so we emulate appending
                return(new CachingAzureStream(blob));
            }
        }
        public void SingDocumentWithPasswordDecrypring()
        {
            //ExStart
            //ExFor:CertificateHolder
            //ExFor:SignOptions.DecryptionPassword
            //ExSummary:Shows how to sign encrypted document file.
            string outputFileName = ArtifactsDir + "Document.Encrypted.docx";

            Document doc = new Document(MyDir + "Document.Encrypted.docx", new LoadOptions("docPassword"));

            // Create certificate holder from a file.
            CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            SignOptions signOptions = new SignOptions
            {
                Comments           = "Comment",
                SignTime           = DateTime.Now,
                DecryptionPassword = "******"
            };

            // Digitally sign encrypted with "docPassword" document in the specified path.
            DigitalSignatureUtil.Sign(doc.OriginalFileName, outputFileName, certificateHolder, signOptions);
            //ExEnd

            // Open encrypted document from a file.
            Document signedDoc = new Document(outputFileName, new LoadOptions("docPassword"));

            // Check that encrypted document was successfully signed.
            DigitalSignatureCollection signatures = signedDoc.DigitalSignatures;

            if (signatures.IsValid && (signatures.Count > 0))
            {
                Assert.Pass(); //The document was signed successfully
            }
        }
Example #4
0
        public void SignDocument()
        {
            //ExStart
            //ExFor:CertificateHolder
            //ExFor:CertificateHolder.Create(String, String)
            //ExFor:DigitalSignatureUtil.Sign(Stream, Stream, CertificateHolder, SignOptions)
            //ExFor:SignOptions.Comments
            //ExFor:SignOptions.SignTime
            //ExSummary:Shows how to sign documents using certificate holder and sign options.
            CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            SignOptions signOptions = new SignOptions {
                Comments = "My comment", SignTime = DateTime.Now
            };

            Stream streamIn  = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open);
            Stream streamOut =
                new FileStream(MyDir + @"\Artifacts\Document.DigitalSignature.docx", FileMode.OpenOrCreate);

            DigitalSignatureUtil.Sign(streamIn, streamOut, certificateHolder, signOptions);
            //ExEnd

            streamIn.Dispose();
            streamOut.Dispose();
        }
        private SignOptions GetSignOptions(string signType, string signText, string signImagePath, string signLocation, string signSize)
        {
            SignOptions signOptions = null;

            if (signType == "barcode")
            {
                signOptions = GetBarcodeSignOptions(signText, signLocation, signSize);
            }
            else if (signType == "qr-code")
            {
                signOptions = GetQRCodeSignOptions(signText, signLocation, signSize);
            }
            else if (signType == "stamp")
            {
                signOptions = GetStampSignOptions(signText, signLocation, signSize);
            }
            else if (signType == "text")
            {
                signOptions = GetTextSignOptions(signText, signLocation, signSize);
            }
            else if (signType == "image")
            {
                signOptions = GetImageSignOptions(signImagePath, signLocation, signSize);
            }
            else if (signType == "digital")
            {
                signOptions = GetDigitalSignOptions(signText, signImagePath, signLocation, signSize);
            }

            return(signOptions);
        }
        public void EncryptedHtml()
        {
            //ExStart
            //ExFor:HtmlLoadOptions.#ctor(String)
            //ExSummary:Shows how to encrypt an Html document, and then open it using a password.
            // Create and sign an encrypted HTML document from an encrypted .docx.
            CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            SignOptions signOptions = new SignOptions
            {
                Comments           = "Comment",
                SignTime           = DateTime.Now,
                DecryptionPassword = "******"
            };

            string inputFileName  = MyDir + "Encrypted.docx";
            string outputFileName = ArtifactsDir + "HtmlLoadOptions.EncryptedHtml.html";

            DigitalSignatureUtil.Sign(inputFileName, outputFileName, certificateHolder, signOptions);

            // To load and read this document, we will need to pass its decryption
            // password using a HtmlLoadOptions object.
            HtmlLoadOptions loadOptions = new HtmlLoadOptions("docPassword");

            Assert.AreEqual(signOptions.DecryptionPassword, loadOptions.Password);

            Document doc = new Document(outputFileName, loadOptions);

            Assert.AreEqual("Test encrypted document.", doc.GetText().Trim());
            //ExEnd
        }
        public void EncryptedHtml()
        {
            //ExStart
            //ExFor:HtmlLoadOptions.#ctor(String)
            //ExSummary:Shows how to encrypt an Html document and then open it using a password.
            // Create and sign an encrypted html document from an encrypted .docx
            CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            SignOptions signOptions = new SignOptions
            {
                Comments           = "Comment",
                SignTime           = DateTime.Now,
                DecryptionPassword = "******"
            };

            string inputFileName  = MyDir + "Encrypted.docx";
            string outputFileName = ArtifactsDir + "HtmlLoadOptions.EncryptedHtml.html";

            DigitalSignatureUtil.Sign(inputFileName, outputFileName, certificateHolder, signOptions);

            // This .html document will need a password to be decrypted, opened and have its contents accessed
            // The password is specified by HtmlLoadOptions.Password
            HtmlLoadOptions loadOptions = new HtmlLoadOptions("docPassword");

            Assert.AreEqual(signOptions.DecryptionPassword, loadOptions.Password);

            Document doc = new Document(outputFileName, loadOptions);

            Assert.AreEqual("Test encrypted document.", doc.GetText().Trim());
            //ExEnd
        }
        /// <summary>
        /// Signs the document obtained at the source location and saves it to the specified destination.
        /// </summary>
        private static void SignDocument(string srcDocumentPath, string dstDocumentPath,
                                         SignPersonTestClass signPersonInfo, string certificatePath, string certificatePassword)
        {
            // Create new document instance based on a test file that we need to sign.
            Document        document = new Document(srcDocumentPath);
            DocumentBuilder builder  = new DocumentBuilder(document);

            // Add info about responsible person who sign a document.
            SignatureLineOptions signatureLineOptions =
                new SignatureLineOptions {
                Signer = signPersonInfo.Name, SignerTitle = signPersonInfo.Position
            };

            // Add signature line for responsible person who sign a document.
            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;

            signatureLine.Id = signPersonInfo.PersonId;

            // Save a document with line signatures into temporary file for future signing.
            builder.Document.Save(dstDocumentPath);

            // Create holder of certificate instance based on your personal certificate.
            // This is the test certificate generated for this example.
            CertificateHolder certificateHolder = CertificateHolder.Create(certificatePath, certificatePassword);

            // Link our signature line with personal signature.
            SignOptions signOptions = new SignOptions
            {
                SignatureLineId    = signPersonInfo.PersonId,
                SignatureLineImage = signPersonInfo.Image
            };

            // Sign a document which contains signature line with personal certificate.
            DigitalSignatureUtil.Sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }
        /// <summary>
        /// Creates a copy of a source document signed using provided signee information and X509 certificate.
        /// </summary>
        private static void SignDocument(string srcDocumentPath, string dstDocumentPath,
                                         Signee signeeInfo, string certificatePath, string certificatePassword)
        {
            Document        document = new Document(srcDocumentPath);
            DocumentBuilder builder  = new DocumentBuilder(document);

            // Configure and insert a signature line, an object in the document that will display a signature that we sign it with.
            SignatureLineOptions signatureLineOptions = new SignatureLineOptions
            {
                Signer      = signeeInfo.Name,
                SignerTitle = signeeInfo.Position
            };

            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;

            signatureLine.Id = signeeInfo.PersonId;

            // First, we will save an unsigned version of our document.
            builder.Document.Save(dstDocumentPath);

            CertificateHolder certificateHolder = CertificateHolder.Create(certificatePath, certificatePassword);

            SignOptions signOptions = new SignOptions
            {
                SignatureLineId    = signeeInfo.PersonId,
                SignatureLineImage = signeeInfo.Image
            };

            // Overwrite the unsigned document we saved above with a version signed using the certificate.
            DigitalSignatureUtil.Sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }
        public void NoArgumentsForSing()
        {
            SignOptions signOptions = new SignOptions {
                Comments = String.Empty, SignTime = DateTime.Now, DecryptionPassword = String.Empty
            };

            Assert.That(() => DigitalSignatureUtil.Sign(String.Empty, String.Empty, null, signOptions),
                        Throws.TypeOf <ArgumentException>());
        }
        public void NoCertificateForSign()
        {
            Document doc            = new Document(MyDir + "Document.DigitalSignature.docx");
            string   outputFileName = MyDir + @"\Artifacts\Document.DigitalSignature.docx";

            SignOptions signOptions = new SignOptions {
                Comments = "Comment", SignTime = DateTime.Now, DecryptionPassword = "******"
            };

            Assert.That(() => DigitalSignatureUtil.Sign(doc.OriginalFileName, outputFileName, null, signOptions),
                        Throws.TypeOf <ArgumentNullException>());
        }
        public void SigningEncryptedDocument()
        {
            //ExStart:SigningEncryptedDocument
            SignOptions signOptions = new SignOptions {
                DecryptionPassword = "******"
            };

            CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            DigitalSignatureUtil.Sign(MyDir + "Digitally signed.docx", ArtifactsDir + "Document.EncryptedDocument.docx",
                                      certHolder, signOptions);
            //ExEnd:SigningEncryptedDocument
        }
        public void SignDocumentObfuscationBug()
        {
            CertificateHolder ch = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            Document doc            = new Document(MyDir + "TestRepeatingSection.docx");
            string   outputFileName = ArtifactsDir + "TestRepeatingSection.Signed.doc";

            SignOptions signOptions = new SignOptions {
                Comments = "Comment", SignTime = DateTime.Now
            };

            DigitalSignatureUtil.Sign(doc.OriginalFileName, outputFileName, ch, signOptions);
        }
Example #14
0
        public void SignDocumentObfuscationBug()
        {
            CertificateHolder ch = CertificateHolder.Create(File.ReadAllBytes(MyDir + "morzal.pfx"), "aw");

            Document doc            = new Document(MyDir + "Structured document tags.docx");
            string   outputFileName = ArtifactsDir + "DigitalSignatureUtil.SignDocumentObfuscationBug.doc";

            SignOptions signOptions = new SignOptions {
                Comments = "Comment", SignTime = DateTime.Now
            };

            DigitalSignatureUtil.Sign(doc.OriginalFileName, outputFileName, ch, signOptions);
        }
        public static void SigningEncryptedDocument(String dataDir)
        {
            // ExStart:SigningEncryptedDocument

            SignOptions signOptions = new SignOptions();

            signOptions.DecryptionPassword = "******";

            CertificateHolder certHolder = CertificateHolder.Create(dataDir + "signature.pfx", "signature");

            DigitalSignatureUtil.Sign(dataDir + "Document.Signed.docx", dataDir + "Document.EncryptedDocument_out.docx", certHolder, signOptions);
            // ExEnd:SigningEncryptedDocument
            Console.WriteLine("\nDocument is signed with successfully.\nFile saved at " + dataDir + "Document.EncryptedDocument_out.docx");
        }
        private static string GetStaffMemberWorkplaceStateCommandString(SignOptions signOptions, string workplaceID, string staffMemberID)
        {
            var action = "SIGNED_ON";

            if (signOptions == SignOptions.Off)
            {
                action = "SIGNED_OFF";
            }
            return("{" +
                   " \"workplaceId\": \"" + workplaceID + "\", " +
                   " \"staffMemberId\": \"" + staffMemberID + "\", " +
                   " \"staffMemberStateId\": \"" + action + "\", " +
                   " \"type\": \"STAFF_MEMBER_WORKPLACE_STATE\" " +
                   "}");
        }
        public void IncorrectPasswordForDecrypring()
        {
            CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            Document doc            = new Document(MyDir + "Document.Encrypted.docx", new LoadOptions("docPassword"));
            string   outputFileName = MyDir + @"\Artifacts\Document.Encrypted.docx";

            SignOptions signOptions = new SignOptions {
                Comments = "Comment", SignTime = DateTime.Now, DecryptionPassword = "******"
            };

            // Digitally sign encrypted with "docPassword" document in the specified path.
            Assert.That(() => DigitalSignatureUtil.Sign(doc.OriginalFileName, outputFileName, certificateHolder, signOptions),
                        Throws.TypeOf <IncorrectPasswordException>(), "The document password is incorrect.");
        }
        public static void SigningExistingSignatureLine(String dataDir)
        {
            // ExStart:SigningExistingSignatureLine
            Document      doc           = new Document(dataDir + "Document.Signed.docx");
            SignatureLine signatureLine = ((Shape)doc.FirstSection.Body.GetChild(NodeType.Shape, 0, true)).SignatureLine;

            SignOptions signOptions = new SignOptions();

            signOptions.SignatureLineId    = signatureLine.Id;
            signOptions.SignatureLineImage = File.ReadAllBytes(dataDir + "SignatureImage.emf");

            CertificateHolder certHolder = CertificateHolder.Create(dataDir + "signature.pfx", "signature");

            DigitalSignatureUtil.Sign(dataDir + "Document.Signed.docx", dataDir + "Document.Signed.ExistingSignatureLine.docx", certHolder, signOptions);
            // ExEnd:SigningExistingSignatureLine

            Console.WriteLine("\nDocument is signed with existing SignatureLine successfully.\nFile saved at " + dataDir + "Document.Signed.ExistingSignatureLine.docx");
        }
Example #19
0
            public ExponentialDecimalOptions(Match match) : base(match)
            {
                Mark = match.Groups["exponent"].Value.Substring(0, 1);

                var signGroup = match.Groups["e_sign"];

                if (signGroup.Success)
                {
                    var sign = signGroup.Value;
                    SignOptions = new SignOptions(sign);
                }

                var flGroup = match.Groups["e_fixedLength"];

                if (flGroup.Success)
                {
                    FixedLength = int.Parse(flGroup.Value);
                }
            }
        public void SetSignatureProviderId()
        {
            //ExStart:SetSignatureProviderID
            Document doc = new Document(MyDir + "Signature line.docx");

            SignatureLine signatureLine =
                ((Shape)doc.FirstSection.Body.GetChild(NodeType.Shape, 0, true)).SignatureLine;

            SignOptions signOptions = new SignOptions
            {
                ProviderId = signatureLine.ProviderId, SignatureLineId = signatureLine.Id
            };

            CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            DigitalSignatureUtil.Sign(MyDir + "Digitally signed.docx",
                                      ArtifactsDir + "SignDocuments.SetSignatureProviderId.docx", certHolder, signOptions);
            //ExEnd:SetSignatureProviderID
        }
        public void SignDocument()
        {
            //ExStart
            //ExFor:CertificateHolder
            //ExFor:CertificateHolder.Create(String, String)
            //ExFor:DigitalSignatureUtil.Sign(Stream, Stream, CertificateHolder, SignOptions)
            //ExFor:SignOptions.Comments
            //ExFor:SignOptions.SignTime
            //ExSummary:Shows how to digitally sign documents.
            // Create an X.509 certificate from a PKCS#12 store, which should contain a private key.
            CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            // Create a comment and date which will be applied with our new digital signature.
            SignOptions signOptions = new SignOptions
            {
                Comments = "My comment",
                SignTime = DateTime.Now
            };

            // Take an unsigned document from the local file system via a file stream,
            // then create a signed copy of it determined by the filename of the output file stream.
            using (Stream streamIn = new FileStream(MyDir + "Document.docx", FileMode.Open))
            {
                using (Stream streamOut = new FileStream(ArtifactsDir + "DigitalSignatureUtil.SignDocument.docx", FileMode.OpenOrCreate))
                {
                    DigitalSignatureUtil.Sign(streamIn, streamOut, certificateHolder, signOptions);
                }
            }
            //ExEnd

            using (Stream stream = new FileStream(ArtifactsDir + "DigitalSignatureUtil.SignDocument.docx", FileMode.Open))
            {
                DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.LoadSignatures(stream);
                Assert.AreEqual(1, digitalSignatures.Count);

                DigitalSignature signature = digitalSignatures[0];

                Assert.True(signature.IsValid);
                Assert.AreEqual(DigitalSignatureType.XmlDsig, signature.SignatureType);
                Assert.AreEqual(signOptions.SignTime.ToString(), signature.SignTime.ToString());
                Assert.AreEqual("My comment", signature.Comments);
            }
        }
        public void SigningExistingSignatureLine()
        {
            //ExStart:SigningExistingSignatureLine
            Document doc = new Document(MyDir + "Signature line.docx");

            SignatureLine signatureLine =
                ((Shape)doc.FirstSection.Body.GetChild(NodeType.Shape, 0, true)).SignatureLine;

            SignOptions signOptions = new SignOptions
            {
                SignatureLineId    = signatureLine.Id,
                SignatureLineImage = File.ReadAllBytes(ImagesDir + "Enhanced Windows MetaFile.emf")
            };

            CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            DigitalSignatureUtil.Sign(MyDir + "Digitally signed.docx",
                                      ArtifactsDir + "SignDocuments.SigningExistingSignatureLine.docx", certHolder, signOptions);
            //ExEnd:SigningExistingSignatureLine
        }
        public static void SetSignatureProviderID(String dataDir)
        {
            // ExStart:SetSignatureProviderID
            Document      doc           = new Document(dataDir + "Document.Signed.docx");
            SignatureLine signatureLine = ((Shape)doc.FirstSection.Body.GetChild(NodeType.Shape, 0, true)).SignatureLine;

            //Set signature and signature line provider ID
            SignOptions signOptions = new SignOptions();

            signOptions.ProviderId      = signatureLine.ProviderId;
            signOptions.SignatureLineId = signatureLine.Id;

            CertificateHolder certHolder = CertificateHolder.Create(dataDir + "signature.pfx", "signature");

            DigitalSignatureUtil.Sign(dataDir + "Document.Signed.docx", dataDir + "Document.Signed_out.docx", certHolder, signOptions);

            // ExEnd:SetSignatureProviderID

            Console.WriteLine("\nProvider ID of signature is set successfully.\nFile saved at " + dataDir + "Document.Signed_out.docx");
        }
        public void IncorrectDecryptionPassword()
        {
            CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            Document doc            = new Document(MyDir + "Encrypted.docx", new LoadOptions("docPassword"));
            string   outputFileName = ArtifactsDir + "DigitalSignatureUtil.IncorrectDecryptionPassword.docx";

            SignOptions signOptions = new SignOptions
            {
                Comments           = "Comment",
                SignTime           = DateTime.Now,
                DecryptionPassword = "******"
            };

#if NET462 || NETCOREAPP2_1 || JAVA
            Assert.That(
                () => DigitalSignatureUtil.Sign(doc.OriginalFileName, outputFileName, certificateHolder, signOptions),
                Throws.TypeOf <IncorrectPasswordException>(), "The document password is incorrect.");
#endif
        }
        public static void CreatingAndSigningNewSignatureLine(String dataDir)
        {
            // ExStart:CreatingAndSigningNewSignatureLine
            Document        doc           = new Document();
            DocumentBuilder builder       = new DocumentBuilder(doc);
            SignatureLine   signatureLine = builder.InsertSignatureLine(new SignatureLineOptions()).SignatureLine;

            doc.Save(dataDir + "Document.NewSignatureLine.docx");

            SignOptions signOptions = new SignOptions();

            signOptions.SignatureLineId    = signatureLine.Id;
            signOptions.SignatureLineImage = File.ReadAllBytes(dataDir + "SignatureImage.emf");

            CertificateHolder certHolder = CertificateHolder.Create(dataDir + "signature.pfx", "signature");

            DigitalSignatureUtil.Sign(dataDir + "Document.NewSignatureLine.docx", dataDir + "Document.NewSignatureLine.docx_out.docx", certHolder, signOptions);
            // ExEnd:CreatingAndSigningNewSignatureLine

            Console.WriteLine("\nDocument is created and Signed with new SignatureLine successfully.\nFile saved at " + dataDir + "Document.NewSignatureLine.docx_out.docx");
        }
        public void CreatingAndSigningNewSignatureLine()
        {
            //ExStart:CreatingAndSigningNewSignatureLine
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            SignatureLine signatureLine = builder.InsertSignatureLine(new SignatureLineOptions()).SignatureLine;

            doc.Save(ArtifactsDir + "SignDocuments.SignatureLine.docx");

            SignOptions signOptions = new SignOptions
            {
                SignatureLineId    = signatureLine.Id,
                SignatureLineImage = File.ReadAllBytes(ImagesDir + "Enhanced Windows MetaFile.emf")
            };

            CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            DigitalSignatureUtil.Sign(ArtifactsDir + "SignDocuments.SignatureLine.docx",
                                      ArtifactsDir + "SignDocuments.NewSignatureLine.docx", certHolder, signOptions);
            //ExEnd:CreatingAndSigningNewSignatureLine
        }
Example #27
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);
    }
        public void DecryptionPassword()
        {
            //ExStart
            //ExFor:CertificateHolder
            //ExFor:SignOptions.DecryptionPassword
            //ExFor:LoadOptions.Password
            //ExSummary:Shows how to sign encrypted document file.
            // Create an X.509 certificate from a PKCS#12 store, which should contain a private key.
            CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            // Create a comment, date, and decryption password which will be applied with our new digital signature.
            SignOptions signOptions = new SignOptions
            {
                Comments           = "Comment",
                SignTime           = DateTime.Now,
                DecryptionPassword = "******"
            };

            // Set a local system filename for the unsigned input document, and an output filename for its new digitally signed copy.
            string inputFileName  = MyDir + "Encrypted.docx";
            string outputFileName = ArtifactsDir + "DigitalSignatureUtil.DecryptionPassword.docx";

            DigitalSignatureUtil.Sign(inputFileName, outputFileName, certificateHolder, signOptions);
            //ExEnd

            // Open encrypted document from a file.
            LoadOptions loadOptions = new LoadOptions("docPassword");

            Assert.AreEqual(signOptions.DecryptionPassword, loadOptions.Password);

            // Check that encrypted document was successfully signed.
            Document signedDoc = new Document(outputFileName, loadOptions);
            DigitalSignatureCollection signatures = signedDoc.DigitalSignatures;

            Assert.AreEqual(1, signatures.Count);
            Assert.True(signatures.IsValid);
        }
        public void CreateNewSignatureLineAndSetProviderId()
        {
            //ExStart:CreateNewSignatureLineAndSetProviderID
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            SignatureLineOptions signatureLineOptions = new SignatureLineOptions
            {
                Signer              = "vderyushev",
                SignerTitle         = "QA",
                Email               = "*****@*****.**",
                ShowDate            = true,
                DefaultInstructions = false,
                Instructions        = "Please sign here.",
                AllowComments       = true
            };

            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;

            signatureLine.ProviderId = Guid.Parse("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2");

            doc.Save(ArtifactsDir + "SignDocuments.SignatureLineProviderId.docx");

            SignOptions signOptions = new SignOptions
            {
                SignatureLineId = signatureLine.Id,
                ProviderId      = signatureLine.ProviderId,
                Comments        = "Document was signed by vderyushev",
                SignTime        = DateTime.Now
            };

            CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            DigitalSignatureUtil.Sign(ArtifactsDir + "SignDocuments.SignatureLineProviderId.docx",
                                      ArtifactsDir + "SignDocuments.CreateNewSignatureLineAndSetProviderId.docx", certHolder, signOptions);
            //ExEnd:CreateNewSignatureLineAndSetProviderID
        }
        public void SignDocument()
        {
            //ExStart
            //ExFor:CertificateHolder
            //ExFor:CertificateHolder.Create(String, String)
            //ExFor:DigitalSignatureUtil.Sign(Stream, Stream, CertificateHolder, SignOptions)
            //ExFor:SignOptions.Comments
            //ExFor:SignOptions.SignTime
            //ExSummary:Shows how to sign documents using certificate holder and sign options.
            CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

            SignOptions signOptions = new SignOptions {
                Comments = "My comment", SignTime = DateTime.Now
            };

            using (Stream streamIn = new FileStream(MyDir + "Digitally signed.docx", FileMode.Open))
            {
                using (Stream streamOut = new FileStream(ArtifactsDir + "DigitalSignatureUtil.SignDocument.docx", FileMode.OpenOrCreate))
                {
                    DigitalSignatureUtil.Sign(streamIn, streamOut, certificateHolder, signOptions);
                }
            }
            //ExEnd

            using (Stream stream = new FileStream(ArtifactsDir + "DigitalSignatureUtil.SignDocument.docx", FileMode.Open))
            {
                DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.LoadSignatures(stream);
                Assert.AreEqual(1, digitalSignatures.Count);

                DigitalSignature signature = digitalSignatures[0];

                Assert.True(signature.IsValid);
                Assert.AreEqual(DigitalSignatureType.XmlDsig, signature.SignatureType);
                Assert.AreEqual(signOptions.SignTime.ToString(), signature.SignTime.ToString());
                Assert.AreEqual("My comment", signature.Comments);
            }
        }