public void SingDocumentWithPasswordDecrypring()
        {
            //ExStart
            //ExFor:DigitalSignatureUtil.Sign(String, String, CertificateHolder, String, DateTime)
            //ExFor:DigitalSignatureUtil.Sign(Stream, Stream, CertificateHolder, String, DateTime)
            //ExSummary:Shows how to sign encrypted documents
            // Create certificate holder from a file.
            CertificateHolder ch = CertificateHolder.Create(MyDir + "certificate.pfx", "123456");

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

            // Digitally sign encrypted with "docPassword" document in the specified path.
            DigitalSignatureUtil.Sign(doc.OriginalFileName, outputDocFileName, ch, "Comment", DateTime.Now, "docPassword");

            // Open encrypted document from a file.
            Document signedDoc = new Document(outputDocFileName, 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
            }
        }
        public static void Run()
        {
            // ExStart:AssignAndValidateDigitalSignatures
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // dsc is signature collection contains one or more signature needed to sign
            DigitalSignatureCollection dsc = new DigitalSignatureCollection();

            // Cert must contain private key, it can be contructed from cert file or windows certificate collection. aa is password of cert
            X509Certificate2 cert = new X509Certificate2(dataDir + "mykey2.pfx", "aa");
            DigitalSignature ds = new DigitalSignature(cert, "test for sign", DateTime.Now);
            dsc.Add(ds);
            Workbook wb = new Workbook();

            // wb.SetDigitalSignature signs all signatures in dsc
            wb.SetDigitalSignature(dsc);
            wb.Save(dataDir + @"newfile_out.xlsx");

            // open the file
            wb = new Workbook(dataDir + @"newfile_out.xlsx");
            System.Console.WriteLine(wb.IsDigitallySigned);

            // Get digitalSignature collection from workbook
            dsc = wb.GetDigitalSignature();
            foreach (DigitalSignature dst in dsc)
            {
                System.Console.WriteLine(dst.Comments); //test for sign -OK
                System.Console.WriteLine(dst.SignTime); //11/25/2010 1:22:01 PM -OK
                System.Console.WriteLine(dst.IsValid); //True -OK
            }
            // ExEnd:AssignAndValidateDigitalSignatures
        }
        public void LoadAndRemove()
        {
            //ExStart
            //ExFor:DigitalSignatureUtil
            //ExFor:DigitalSignatureUtil.LoadSignatures(String)
            //ExFor:DigitalSignatureUtil.LoadSignatures(Stream)
            //ExFor:DigitalSignatureUtil.RemoveAllSignatures(Stream, Stream)
            //ExFor:DigitalSignatureUtil.RemoveAllSignatures(String, String)
            //ExSummary:Shows how to load and remove digital signatures from a digitally signed document.
            // Load digital signatures via filename string to verify that the document is signed
            DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.LoadSignatures(MyDir + "Digitally signed.docx");

            Assert.AreEqual(1, digitalSignatures.Count);

            // Re-save the document to an output filename with all digital signatures removed
            DigitalSignatureUtil.RemoveAllSignatures(MyDir + "Digitally signed.docx", ArtifactsDir + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");

            // Remove all signatures from the document using stream parameters
            using (Stream streamIn = new FileStream(MyDir + "Digitally signed.docx", FileMode.Open))
            {
                using (Stream streamOut = new FileStream(ArtifactsDir + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx", FileMode.Create))
                {
                    DigitalSignatureUtil.RemoveAllSignatures(streamIn, streamOut);
                }
            }

            // We can also load a document's digital signatures via stream, which we will do to verify that all signatures have been removed
            using (Stream stream = new FileStream(ArtifactsDir + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx", FileMode.Open))
            {
                digitalSignatures = DigitalSignatureUtil.LoadSignatures(stream);
                Assert.AreEqual(0, digitalSignatures.Count);
            }
            //ExEnd
        }
        public static void Run()
        {
            // ExStart:1
            //Source directory
            string sourceDir = RunExamples.Get_SourceDirectory();

            //Output directory
            string outputDir = RunExamples.Get_OutputDirectory();

            Workbook workbook = new Workbook(sourceDir + "sourceFile.xlsx");
            string   password = "******";
            string   pfx      = "pfxFile";

            DigitalSignature signature = new DigitalSignature(File.ReadAllBytes(pfx), password, "testXAdES", DateTime.Now);

            signature.XAdESType = XAdESType.XAdES;
            DigitalSignatureCollection dsCollection = new DigitalSignatureCollection();

            dsCollection.Add(signature);

            workbook.SetDigitalSignature(dsCollection);

            workbook.Save(outputDir + "XAdESSignatureSupport_out.xlsx");
            // ExEnd:1

            Console.WriteLine("XAdESSignatureSupport executed successfully.");
        }
示例#5
0
        /*
         * Processes the given signature collection.
         */
        void ProcessSignatures(Node entityNode, DigitalSignatureCollection signatures)
        {
            // Making sure there are any signatures.
            if (signatures == null)
            {
                return;
            }

            // Looping through each signature.
            foreach (var idxSignature in signatures)
            {
                // We cannot verify signatures unless we have the public PGP key in GnuPG database, hence the try thingie ...
                try {
                    // Making sure we return email of PGP key used to sign, and true as value of node if signature is valid.
                    var signatureNode = entityNode.FindOrInsert("signature").Add(idxSignature.SignerCertificate.Email, idxSignature.Verify()).LastChild;

                    // Adding fingerprint of PGP key used to sign entity.
                    signatureNode.Add("fingerprint", idxSignature.SignerCertificate.Fingerprint);
                } catch {
                    // Inserting unknown fingerprint and signature email.
                    var signatureNode = entityNode.FindOrInsert("signature").Add("unknown", false).LastChild;
                    signatureNode.Add("fingerprint", "unknown");
                }
            }
        }
        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
            }
        }
        public void SingStreamDocumentWithPasswordDecrypring()
        {
            // Create certificate holder from a file.
            CertificateHolder ch = CertificateHolder.Create(MyDir + "certificate.pfx", "123456");

            //By Stream
            Stream docInStream  = new FileStream(MyDir + "Document.Encrypted.docx", FileMode.Open);
            Stream docOutStream = new FileStream(MyDir + @"\Artifacts\Document.Encrypted.docx", FileMode.OpenOrCreate);

            // Digitally sign encrypted with "docPassword" document in the specified path.
            DigitalSignatureUtil.Sign(docInStream, docOutStream, ch, "Comment", DateTime.Now, "docPassword");

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

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

            if (signatures.IsValid && (signatures.Count > 0))
            {
                docInStream.Dispose();
                docOutStream.Dispose();

                Assert.Pass(); //The document was signed successfully
            }
        }
        public static void Run()
        {
            // ExStart:AssignAndValidateDigitalSignatures
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // dsc is signature collection contains one or more signature needed to sign
            DigitalSignatureCollection dsc = new DigitalSignatureCollection();

            // Cert must contain private key, it can be contructed from cert file or windows certificate collection. aa is password of cert
            X509Certificate2 cert = new X509Certificate2(dataDir + "mykey2.pfx", "aa");
            DigitalSignature ds   = new DigitalSignature(cert, "test for sign", DateTime.Now);

            dsc.Add(ds);
            Workbook wb = new Workbook();

            // wb.SetDigitalSignature signs all signatures in dsc
            wb.SetDigitalSignature(dsc);
            wb.Save(dataDir + @"newfile_out.xlsx");

            // open the file
            wb = new Workbook(dataDir + @"newfile_out.xlsx");
            System.Console.WriteLine(wb.IsDigitallySigned);

            // Get digitalSignature collection from workbook
            dsc = wb.GetDigitalSignature();
            foreach (DigitalSignature dst in dsc)
            {
                System.Console.WriteLine(dst.Comments); //test for sign -OK
                System.Console.WriteLine(dst.SignTime); //11/25/2010 1:22:01 PM -OK
                System.Console.WriteLine(dst.IsValid);  //True -OK
            }
            // ExEnd:AssignAndValidateDigitalSignatures
        }
示例#9
0
        public void GetEnumerator()
        {
            //ExStart
            //ExFor:DigitalSignatureCollection.GetEnumerator
            //ExSummary:Shows how to load and enumerate all digital signatures of a document.
            DigitalSignatureCollection digitalSignatures =
                DigitalSignatureUtil.LoadSignatures(MyDir + "Digitally signed.docx");

            using (IEnumerator <DigitalSignature> enumerator = digitalSignatures.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    // Do something useful
                    DigitalSignature ds = enumerator.Current;

                    if (ds != null)
                    {
                        Console.WriteLine(ds.ToString());
                    }
                }
            }
            //ExEnd

            Assert.AreEqual(1, digitalSignatures.Count);

            DigitalSignature signature = digitalSignatures[0];

            Assert.True(signature.IsValid);
            Assert.AreEqual(DigitalSignatureType.XmlDsig, signature.SignatureType);
            Assert.AreEqual("12/23/2010 02:14:40 AM", signature.SignTime.ToString("MM/dd/yyyy hh:mm:ss tt"));
            Assert.AreEqual("Test Sign", signature.Comments);

            Assert.AreEqual(signature.IssuerName, signature.CertificateHolder.Certificate.IssuerName.Name);
            Assert.AreEqual(signature.SubjectName, signature.CertificateHolder.Certificate.SubjectName.Name);

            Assert.AreEqual("CN=VeriSign Class 3 Code Signing 2009-2 CA, " +
                            "OU=Terms of use at https://www.verisign.com/rpa (c)09, " +
                            "OU=VeriSign Trust Network, " +
                            "O=\"VeriSign, Inc.\", " +
                            "C=US", signature.IssuerName);

            Assert.AreEqual("CN=Aspose Pty Ltd, " +
                            "OU=Digital ID Class 3 - Microsoft Software Validation v2, " +
                            "O=Aspose Pty Ltd, " +
                            "L=Lane Cove, " +
                            "S=New South Wales, " +
                            "C=AU", signature.SubjectName);
        }
示例#10
0
        /*
         * Processes the given signature collection.
         */
        void ProcessSignatures(Node entityNode, DigitalSignatureCollection signatures)
        {
            // Making sure there are any signatures.
            if (signatures == null)
            {
                return; // Nothing to do here ...
            }
            // Looping through each signature.
            foreach (var idxSignature in signatures)
            {
                // Making sure we return email of PGP key used to sign, and true as value of node if signature is valid.
                var signatureNode = entityNode.FindOrInsert("signature").Add(idxSignature.SignerCertificate.Email, idxSignature.Verify()).LastChild;

                // Adding fingerprint of PGP key used to sign entity.
                signatureNode.Add("fingerprint", idxSignature.SignerCertificate.Fingerprint.ToLower());
            }
        }
        public void LoadSignaturesEx()
        {
            //ExStart
            //ExFor:DigitalSignatureUtil.LoadSignatures(Stream)
            //ExFor:DigitalSignatureUtil.LoadSignatures(String)
            //ExSummary:Shows how to load signatures from a document by stream and by string.
            Stream docStream = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open);

            // By stream:
            DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.LoadSignatures(docStream);

            docStream.Close();

            // By string:
            digitalSignatures = DigitalSignatureUtil.LoadSignatures(MyDir + "Document.DigitalSignature.docx");
            //ExEnd
        }
        public void GetEnumeratorEx()
        {
            //ExStart
            //ExFor:DigitalSignatureCollection.GetEnumerator
            //ExSummary:Shows how to load and enumerate all digital signatures of a document.
            DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.LoadSignatures(MyDir + "Document.Signed.doc");

            var enumerator = digitalSignatures.GetEnumerator();

            while (enumerator.MoveNext())
            {
                // Do something useful
                DigitalSignature ds = (DigitalSignature)enumerator.Current;
                Console.WriteLine(ds.ToString());
            }
            //ExEnd
        }
        public void LoadSignatures()
        {
            //ExStart
            //ExFor:DigitalSignatureUtil.LoadSignatures(Stream)
            //ExFor:DigitalSignatureUtil.LoadSignatures(String)
            //ExSummary:Shows how to load all existing signatures from a document.
            // By string:
            DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.LoadSignatures(MyDir + "Document.DigitalSignature.docx");

            // By stream:
            Stream stream = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open);

            digitalSignatures = DigitalSignatureUtil.LoadSignatures(stream);
            //ExEnd

            stream.Close();
        }
        public void LoadSignatures()
        {
            //ExStart
            //ExFor:DigitalSignatureUtil.LoadSignatures(Stream)
            //ExFor:DigitalSignatureUtil.LoadSignatures(String)
            //ExSummary:Shows how to load all existing signatures from a document.
            // Load all signatures from the document using string parameters
            DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.LoadSignatures(MyDir + "Document.DigitalSignature.docx");

            Assert.NotNull(digitalSignatures);

            // Load all signatures from the document using stream parameters
            Stream stream = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open);

            digitalSignatures = DigitalSignatureUtil.LoadSignatures(stream);
            //ExEnd

            stream.Close();
        }
        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 GetEnumerator()
        {
            //ExStart
            //ExFor:DigitalSignatureCollection.GetEnumerator
            //ExSummary:Shows how to load and enumerate all digital signatures of a document.
            DigitalSignatureCollection digitalSignatures =
                DigitalSignatureUtil.LoadSignatures(MyDir + "Document.DigitalSignature.docx");

            using (IEnumerator<DigitalSignature> enumerator = digitalSignatures.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    // Do something useful
                    DigitalSignature ds = enumerator.Current;

                    if (ds != null)
                        Console.WriteLine(ds.ToString());
                }
            }

            //ExEnd
        }
        public void Load()
        {
            //ExStart
            //ExFor:DigitalSignatureUtil
            //ExFor:DigitalSignatureUtil.LoadSignatures(String)
            //ExFor:DigitalSignatureUtil.LoadSignatures(Stream)
            //ExSummary:Shows how to load signatures from a digitally signed document.
            // There are two ways of loading a signed document's collection of digital signatures using the DigitalSignatureUtil class.
            // 1 -  Load from a document from a local file system filename:
            DigitalSignatureCollection digitalSignatures =
                DigitalSignatureUtil.LoadSignatures(MyDir + "Digitally signed.docx");

            // If this collection is nonempty, then we can verify that the document is digitally signed.
            Assert.AreEqual(1, digitalSignatures.Count);

            // 2 -  Load from a document from a FileStream:
            using (Stream stream = new FileStream(MyDir + "Digitally signed.docx", FileMode.Open))
            {
                digitalSignatures = DigitalSignatureUtil.LoadSignatures(stream);
                Assert.AreEqual(1, digitalSignatures.Count);
            }
            //ExEnd
        }
        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 static void Run()
        {
            //Source directory
            string sourceDir = RunExamples.Get_SourceDirectory();

            //Output directory
            string outputDir = RunExamples.Get_OutputDirectory();

            // dsc is signature collection contains one or more signature needed to sign
            DigitalSignatureCollection dsc = new DigitalSignatureCollection();

            // Cert must contain private key, it can be contructed from cert file or windows certificate collection. aa is password of cert
            X509Certificate2 cert = new X509Certificate2(sourceDir + "sampleAssignAndValidateDigitalSignatures.pfx", "aa");
            DigitalSignature ds   = new DigitalSignature(cert, "test for sign", DateTime.Now);

            dsc.Add(ds);
            Workbook wb = new Workbook();

            // wb.SetDigitalSignature signs all signatures in dsc
            wb.SetDigitalSignature(dsc);
            wb.Save(outputDir + @"outputAssignAndValidateDigitalSignatures.xlsx");

            // open the file
            wb = new Workbook(outputDir + @"outputAssignAndValidateDigitalSignatures.xlsx");
            System.Console.WriteLine(wb.IsDigitallySigned);

            // Get digitalSignature collection from workbook
            dsc = wb.GetDigitalSignature();
            foreach (DigitalSignature dst in dsc)
            {
                System.Console.WriteLine(dst.Comments); //test for sign -OK
                System.Console.WriteLine(dst.SignTime); //11/25/2010 1:22:01 PM -OK
                System.Console.WriteLine(dst.IsValid);  //True -OK
            }

            Console.WriteLine("AssignAndValidateDigitalSignatures executed successfully.");
        }
        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);
            }
        }
示例#21
0
        public bool VerifySignature(MultipartSigned multipartSigned, out DigitalSignatureCollection signatures)
        {
            var signed = multipartSigned;

            signatures = null;
            var valid = true;

            if (signed != null)
            {
                using (var ctx = this.secureContextFactory())
                {
                    signatures = signed.Verify(ctx);
                    foreach (var signature in signatures)
                    {
                        valid = signature.Verify();
                        if (!valid)
                        {
                            break;
                        }
                    }
                }
            }
            return(valid);
        }
        public void DecryptionPassword()
        {
            //ExStart
            //ExFor:CertificateHolder
            //ExFor:SignOptions.DecryptionPassword
            //ExFor:LoadOptions.Password
            //ExSummary:Shows how to sign encrypted document file.
            // 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
            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);
        }
示例#23
0
        /// <summary>
        /// Decrypt an encrypted stream.
        /// </summary>
        /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
        /// <param name="encryptedData">The encrypted data.</param>
        /// <param name="signatures">A list of digital signatures if the data was both signed and encrypted.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="encryptedData"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="PrivateKeyNotFoundException">
        /// The private key could not be found to decrypt the stream.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The user chose to cancel the password prompt.
        /// </exception>
        /// <exception cref="System.UnauthorizedAccessException">
        /// 3 bad attempts were made to unlock the secret key.
        /// </exception>
        public MimeEntity Decrypt(Stream encryptedData, out DigitalSignatureCollection signatures)
        {
            if (encryptedData == null)
                throw new ArgumentNullException ("encryptedData");

            // FIXME: document the exceptions that can be thrown by BouncyCastle
            using (var armored = new ArmoredInputStream (encryptedData)) {
                var factory = new PgpObjectFactory (armored);
                var obj = factory.NextPgpObject ();
                var list = obj as PgpEncryptedDataList;

                if (list == null) {
                    // probably a PgpMarker...
                    obj = factory.NextPgpObject ();

                    list = obj as PgpEncryptedDataList;
                    if (list == null)
                        throw new Exception ("Unexpected pgp object");
                }

                PgpPublicKeyEncryptedData encrypted = null;
                foreach (PgpEncryptedData data in list.GetEncryptedDataObjects ()) {
                    if ((encrypted = data as PgpPublicKeyEncryptedData) != null)
                        break;
                }

                if (encrypted == null)
                    throw new Exception ("no encrypted data objects found?");

                factory = new PgpObjectFactory (encrypted.GetDataStream (GetPrivateKey (encrypted.KeyId)));
                PgpOnePassSignatureList onepassList = null;
                PgpSignatureList signatureList = null;
                PgpCompressedData compressed = null;

                using (var memory = new MemoryStream ()) {
                    obj = factory.NextPgpObject ();
                    while (obj != null) {
                        if (obj is PgpCompressedData) {
                            if (compressed != null)
                                throw new Exception ("recursive compression detected.");

                            compressed = (PgpCompressedData) obj;
                            factory = new PgpObjectFactory (compressed.GetDataStream ());
                        } else if (obj is PgpOnePassSignatureList) {
                            onepassList = (PgpOnePassSignatureList) obj;
                        } else if (obj is PgpSignatureList) {
                            signatureList = (PgpSignatureList) obj;
                        } else if (obj is PgpLiteralData) {
                            var literal = (PgpLiteralData) obj;

                            using (var stream = literal.GetDataStream ()) {
                                stream.CopyTo (memory, 4096);
                            }
                        }

                        obj = factory.NextPgpObject ();
                    }

                    memory.Position = 0;

                    // FIXME: validate the OnePass signatures... and do what with them?
            //					if (onepassList != null) {
            //						for (int i = 0; i < onepassList.Count; i++) {
            //							var onepass = onepassList[i];
            //						}
            //					}

                    if (signatureList != null) {
                        signatures = GetDigitalSignatures (signatureList, memory);
                        memory.Position = 0;
                    } else {
                        signatures = null;
                    }

                    return MimeEntity.Load (memory);
                }
            }
        }
		/// <summary>
		/// Decrypts the specified encryptedData and extracts the digital signers if the content was also signed.
		/// </summary>
		/// <remarks>
		/// Decrypts the specified encryptedData and extracts the digital signers if the content was also signed.
		/// </remarks>
		/// <returns>The decrypted stream.</returns>
		/// <param name="encryptedData">The encrypted data.</param>
		/// <param name="signatures">A list of digital signatures if the data was both signed and encrypted.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="encryptedData"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key could not be found to decrypt the stream.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
		/// An OpenPGP error occurred.
		/// </exception>
		public Stream GetDecryptedStream (Stream encryptedData, out DigitalSignatureCollection signatures)
		{
			if (encryptedData == null)
				throw new ArgumentNullException ("encryptedData");

			using (var armored = new ArmoredInputStream (encryptedData)) {
				var factory = new PgpObjectFactory (armored);
				var obj = factory.NextPgpObject ();
				var list = obj as PgpEncryptedDataList;

				if (list == null) {
					// probably a PgpMarker...
					obj = factory.NextPgpObject ();

					list = obj as PgpEncryptedDataList;

					if (list == null)
						throw new PgpException ("Unexpected OpenPGP packet.");
				}

				PgpPublicKeyEncryptedData encrypted = null;
				PrivateKeyNotFoundException pkex = null;
				bool hasEncryptedPackets = false;
				PgpSecretKey secret = null;

				foreach (PgpEncryptedData data in list.GetEncryptedDataObjects ()) {
					if ((encrypted = data as PgpPublicKeyEncryptedData) == null)
						continue;

					hasEncryptedPackets = true;

					try {
						secret = GetSecretKey (encrypted.KeyId);
						break;
					} catch (PrivateKeyNotFoundException ex) {
						pkex = ex;
					}
				}

				if (!hasEncryptedPackets)
					throw new PgpException ("No encrypted packets found.");

				if (secret == null)
					throw pkex;

				factory = new PgpObjectFactory (encrypted.GetDataStream (GetPrivateKey (secret)));
				List<IDigitalSignature> onepassList = null;
				PgpSignatureList signatureList = null;
				PgpCompressedData compressed = null;
				var memory = new MemoryBlockStream ();

				obj = factory.NextPgpObject ();
				while (obj != null) {
					if (obj is PgpCompressedData) {
						if (compressed != null)
							throw new PgpException ("Recursive compression packets are not supported.");

						compressed = (PgpCompressedData) obj;
						factory = new PgpObjectFactory (compressed.GetDataStream ());
					} else if (obj is PgpOnePassSignatureList) {
						if (memory.Length == 0) {
							var onepasses = (PgpOnePassSignatureList) obj;

							onepassList = new List<IDigitalSignature> ();

							for (int i = 0; i < onepasses.Count; i++) {
								var onepass = onepasses[i];
								var pubkey = PublicKeyRingBundle.GetPublicKey (onepass.KeyId);

								if (pubkey == null) {
									// too messy, pretend we never found a one-pass signature list
									onepassList = null;
									break;
								}

								onepass.InitVerify (pubkey);

								var signature = new OpenPgpDigitalSignature (pubkey, onepass) {
									PublicKeyAlgorithm = GetPublicKeyAlgorithm (onepass.KeyAlgorithm),
									DigestAlgorithm = GetDigestAlgorithm (onepass.HashAlgorithm),
								};

								onepassList.Add (signature);
							}
						}
					} else if (obj is PgpSignatureList) {
						signatureList = (PgpSignatureList) obj;
					} else if (obj is PgpLiteralData) {
						var literal = (PgpLiteralData) obj;

						using (var stream = literal.GetDataStream ()) {
							var buffer = new byte[4096];
							int nread;

							while ((nread = stream.Read (buffer, 0, buffer.Length)) > 0) {
								if (onepassList != null) {
									// update our one-pass signatures...
									for (int index = 0; index < nread; index++) {
										byte c = buffer[index];

										for (int i = 0; i < onepassList.Count; i++) {
											var pgp = (OpenPgpDigitalSignature) onepassList[i];
											pgp.OnePassSignature.Update (c);
										}
									}
								}

								memory.Write (buffer, 0, nread);
							}
						}
					}

					obj = factory.NextPgpObject ();
				}

				memory.Position = 0;

				if (signatureList != null) {
					if (onepassList != null && signatureList.Count == onepassList.Count) {
						for (int i = 0; i < onepassList.Count; i++) {
							var pgp = (OpenPgpDigitalSignature) onepassList[i];
							pgp.CreationDate = signatureList[i].CreationTime;
							pgp.Signature = signatureList[i];
						}

						signatures = new DigitalSignatureCollection (onepassList);
					} else {
						signatures = GetDigitalSignatures (signatureList, memory);
						memory.Position = 0;
					}
				} else {
					signatures = null;
				}

				return memory;
			}
		}
		/// <summary>
		/// Decrypts the specified encryptedData and extracts the digital signers if the content was also signed.
		/// </summary>
		/// <remarks>
		/// Decrypts the specified encryptedData and extracts the digital signers if the content was also signed.
		/// </remarks>
		/// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
		/// <param name="encryptedData">The encrypted data.</param>
		/// <param name="signatures">A list of digital signatures if the data was both signed and encrypted.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="encryptedData"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key could not be found to decrypt the stream.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
		/// An OpenPGP error occurred.
		/// </exception>
		public MimeEntity Decrypt (Stream encryptedData, out DigitalSignatureCollection signatures)
		{
			if (encryptedData == null)
				throw new ArgumentNullException ("encryptedData");

			var decrypted = GetDecryptedStream (encryptedData, out signatures);

			return MimeEntity.Load (decrypted, true);
		}
示例#26
0
		/// <summary>
		/// Decrypts the <see cref="MultipartEncrypted"/> part.
		/// </summary>
		/// <remarks>
		/// Decrypts the <see cref="MultipartEncrypted"/> and extracts any digital signatures in cases
		/// where the content was also signed.
		/// </remarks>
		/// <returns>The decrypted entity.</returns>
		/// <param name="signatures">A list of digital signatures if the data was both signed and encrypted.</param>
		/// <exception cref="System.FormatException">
		/// <para>The <c>protocol</c> parameter was not specified.</para>
		/// <para>-or-</para>
		/// <para>The multipart is malformed in some way.</para>
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// A suitable <see cref="MimeKit.Cryptography.CryptographyContext"/> for
		/// decrypting could not be found.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key could not be found to decrypt the encrypted data.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public MimeEntity Decrypt (out DigitalSignatureCollection signatures)
		{
			var protocol = ContentType.Parameters["protocol"];
			if (string.IsNullOrEmpty (protocol))
				throw new FormatException ();

			protocol = protocol.Trim ().ToLowerInvariant ();

			if (Count < 2)
				throw new FormatException ();

			var version = this[0] as MimePart;
			if (version == null)
				throw new FormatException ();

			var ctype = version.ContentType;
			var value = string.Format ("{0}/{1}", ctype.MediaType, ctype.MediaSubtype);
			if (value.ToLowerInvariant () != protocol)
				throw new FormatException ();

			var encrypted = this[1] as MimePart;
			if (encrypted == null || encrypted.ContentObject == null)
				throw new FormatException ();

			if (!encrypted.ContentType.Matches ("application", "octet-stream"))
				throw new FormatException ();

			using (var ctx = CryptographyContext.Create (protocol)) {
				using (var memory = new MemoryStream ()) {
					var pgp = ctx as OpenPgpContext;

					encrypted.ContentObject.DecodeTo (memory);
					memory.Position = 0;

					if (pgp != null)
						return pgp.Decrypt (memory, out signatures);

					signatures = null;

					return ctx.Decrypt (memory);
				}
			}
		}
示例#27
0
		/// <summary>
		/// Decrypts the <see cref="MultipartEncrypted"/> part.
		/// </summary>
		/// <remarks>
		/// Decrypts the <see cref="MultipartEncrypted"/> and extracts any digital signatures in cases
		/// where the content was also signed.
		/// </remarks>
		/// <returns>The decrypted entity.</returns>
		/// <param name="ctx">The OpenPGP cryptography context to use for decrypting.</param>
		/// <param name="signatures">A list of digital signatures if the data was both signed and encrypted.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="ctx"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.FormatException">
		/// <para>The <c>protocol</c> parameter was not specified.</para>
		/// <para>-or-</para>
		/// <para>The multipart is malformed in some way.</para>
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The provided <see cref="OpenPgpContext"/> does not support the protocol parameter.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key could not be found to decrypt the encrypted data.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public MimeEntity Decrypt (OpenPgpContext ctx, out DigitalSignatureCollection signatures)
		{
			if (ctx == null)
				throw new ArgumentNullException ("ctx");

			var protocol = ContentType.Parameters["protocol"];
			if (string.IsNullOrEmpty (protocol))
				throw new FormatException ();

			protocol = protocol.Trim ().ToLowerInvariant ();
			if (!ctx.Supports (protocol))
				throw new NotSupportedException ();

			if (Count < 2)
				throw new FormatException ();

			var version = this[0] as MimePart;
			if (version == null)
				throw new FormatException ();

			var ctype = version.ContentType;
			var value = string.Format ("{0}/{1}", ctype.MediaType, ctype.MediaSubtype);
			if (value.ToLowerInvariant () != protocol)
				throw new FormatException ();

			var encrypted = this[1] as MimePart;
			if (encrypted == null || encrypted.ContentObject == null)
				throw new FormatException ();

			if (!encrypted.ContentType.Matches ("application", "octet-stream"))
				throw new FormatException ();

			using (var memory = new MemoryStream ()) {
				encrypted.ContentObject.DecodeTo (memory);
				memory.Position = 0;

				return ctx.Decrypt (memory, out signatures);
			}
		}