예제 #1
0
        public virtual void TestSecureMimeEncryption()
        {
            var certificate = new X509Certificate2(Path.Combine("..", "..", "TestData", "smime", "smime.p12"), "no.secret");
            var body        = new TextPart("plain")
            {
                Text = "This is some cleartext that we'll end up encrypting..."
            };
            var recipients = new CmsRecipientCollection();

            recipients.Add(new CmsRecipient(certificate, SubjectIdentifierType.SubjectKeyIdentifier));

            using (var ctx = CreateContext()) {
                var encrypted = ApplicationPkcs7Mime.Encrypt(ctx, recipients, body);

                Assert.AreEqual(SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match.");

                using (var stream = new MemoryStream()) {
                    ctx.DecryptTo(encrypted.ContentObject.Open(), stream);
                    stream.Position = 0;

                    var decrypted = MimeEntity.Load(stream);

                    Assert.IsInstanceOf <TextPart> (decrypted, "Decrypted part is not the expected type.");
                    Assert.AreEqual(body.Text, ((TextPart)decrypted).Text, "Decrypted content is not the same as the original.");
                }
            }
        }
예제 #2
0
        public async Task Encrypt_VS_Decrypt(string fileName)
        {
            var stream = await GetAssetStreamAsync(fileName);

            var context = new TestSecureContext(
                await GetFromPemFileAsync <X509Certificate>("pem.pem", "password"),
                EncryptionAlgorithm.TripleDes,
                await GetFromPemFileAsync <RsaPrivateCrtKeyParameters>("pem.pem", "password"));

            var encrypted = ApplicationPkcs7Mime.Encrypt(
                context,
                new List <MailboxAddress>
            {
                new MailboxAddress(string.Empty)
            },
                new MimePart
            {
                Content = new MimeContent(stream)
            });

            var decrypted = encrypted.Decrypt(context);

            Assert.IsInstanceOf <MimePart>(decrypted);
            FileAssert.AreEqual(stream, ((MimePart)decrypted).Content.Stream);
        }
         static void Main (string[] args)
 		{
 			//  Select a binary file
 			var dialog = new OpenFileDialog {
 				Filter = "All files (*.*)|*.*",
 				InitialDirectory = "./",
 				Title = "Select a text file"
 			};
 			var filename = (dialog.ShowDialog () == DialogResult.OK) ? dialog.FileName : null;
             var certificate2 = new X509Certificate2 ("c:/temp1/cert.pfx", "password");
             MimeEntity body;
 
 			using (var content = new MemoryStream (File.ReadAllBytes (filename)))
 			    var part = new MimePart (MimeTypes.GetMimeType (filename)) {
 				    ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
 				    ContentTransferEncoding = ContentEncoding.Binary,
 				    FileName = Path.GetFileName (filename),
 				    Content = new MimeContent (content)
 			    };
 
 			    var recipient = new CmsRecipient (certificate2) {
                     EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes }
                 };
                 var recipients = new CmsRecipientCollection ();
 			    recipients.Add (recipient);
 
 			    using (var ctx = new TemporarySecureMimeContext ())
 				    body = ApplicationPkcs7Mime.Encrypt (ctx, recipients, part);
 			}
예제 #4
0
 /*
  * tries to encrypt a MimeEntity
  */
 public static MimeEntity EncryptEntity(MimeEntity entity, IEnumerable <MailboxAddress> list)
 {
     using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
     {
         return(ApplicationPkcs7Mime.Encrypt(ctx, list, entity));
     }
 }
예제 #5
0
 /*
  * returns true if email can be encrypted
  */
 public static string CanEncrypt(Node emails)
 {
     if (emails.Count == 0)
     {
         return("there are no recipients");
     }
     try
     {
         List <MailboxAddress> list = new List <MailboxAddress>();
         foreach (Node idx in emails)
         {
             list.Add(new MailboxAddress("", idx.Get <string>()));
         }
         TextPart entity = new TextPart("text");
         using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
         {
             ApplicationPkcs7Mime.Encrypt(ctx, list, entity);
         }
         return(null);
     }
     catch (Exception err)
     {
         return(err.Message);
     }
 }
예제 #6
0
 public void Encrypt(MimeMessage message)
 {
     // encrypt our message body using our custom S/MIME cryptography context
     using (var ctx = new MySecureMimeContext()) {
         // Note: this assumes that each of the recipients has an S/MIME certificate
         // with an X.509 Subject Email identifier that matches their email address.
         //
         // If this is not the case, you can use SecureMailboxAddresses instead of
         // normal MailboxAddresses which would allow you to specify the fingerprint
         // of their certificates. You could also choose to use one of the Encrypt()
         // overloads that take a list of CmsRecipients, instead.
         message.Body = ApplicationPkcs7Mime.Encrypt(ctx, message.To.Mailboxes, message.Body);
     }
 }
예제 #7
0
        public static bool SendEncryptMessage(MimeMessage message)
        {
            bool isSuccess = false;

            try
            {
                using (var ctx = new SecureMimeContext())
                {
                    message.Body = ApplicationPkcs7Mime.Encrypt(ctx, message.To.Mailboxes, message.Body);
                    SendEmailByMailServer(message);
                    isSuccess = true;
                }
                return(isSuccess);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException.ToString());
                return(isSuccess);
            }
        }
예제 #8
0
        public void TestSecureMimeEncryption()
        {
            var self       = new MailboxAddress("MimeKit UnitTests", "*****@*****.**");
            var recipients = new List <MailboxAddress> ();

            // encrypt to ourselves...
            recipients.Add(self);

            var cleartext = new TextPart("plain");

            cleartext.Text = "This is some cleartext that we'll end up encrypting...";

            using (var ctx = CreateContext()) {
                var encrypted = ApplicationPkcs7Mime.Encrypt(ctx, recipients, cleartext);

                Assert.AreEqual(SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match.");

                var decrypted = encrypted.Decrypt(ctx);

                Assert.IsInstanceOfType(typeof(TextPart), decrypted, "Decrypted part is not the expected type.");
                Assert.AreEqual(cleartext.Text, ((TextPart)decrypted).Text, "Decrypted content is not the same as the original.");
            }
        }
예제 #9
0
        public void TestArgumentExceptions()
        {
            var path   = Path.Combine("..", "..", "TestData", "smime", "smime.p12");
            var entity = new TextPart("plain")
            {
                Text = "This is some text..."
            };
            var mailbox    = new MailboxAddress("MimeKit UnitTests", "*****@*****.**");
            var recipients = new CmsRecipientCollection();
            var signer     = new CmsSigner(path, "no.secret");
            var mailboxes  = new [] { mailbox };

            recipients.Add(new CmsRecipient(signer.Certificate));

            using (var ctx = new TemporarySecureMimeContext()) {
                using (var file = File.OpenRead(path))
                    ctx.Import(file, "no.secret");

                // Compress
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Compress(null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Compress(ctx, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Compress(null));

                // Encrypt
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(null, mailboxes, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(null, recipients, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(ctx, (IEnumerable <MailboxAddress>)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(ctx, (CmsRecipientCollection)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(ctx, recipients, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(ctx, mailboxes, null));

                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt((IEnumerable <MailboxAddress>)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt((CmsRecipientCollection)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(recipients, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt(mailboxes, null));

                // Sign
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(null, mailbox, DigestAlgorithm.Sha1, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(null, signer, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(ctx, (MailboxAddress)null, DigestAlgorithm.Sha1, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(ctx, (CmsSigner)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(ctx, mailbox, DigestAlgorithm.Sha1, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(ctx, signer, null));

                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign((MailboxAddress)null, DigestAlgorithm.Sha1, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign((CmsSigner)null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(mailbox, DigestAlgorithm.Sha1, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.Sign(signer, null));

                // SignAndEncrypt
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(null, mailbox, DigestAlgorithm.Sha1, mailboxes, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, null, DigestAlgorithm.Sha1, mailboxes, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, mailbox, DigestAlgorithm.Sha1, null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, mailbox, DigestAlgorithm.Sha1, mailboxes, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(null, DigestAlgorithm.Sha1, mailboxes, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(mailbox, DigestAlgorithm.Sha1, null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(mailbox, DigestAlgorithm.Sha1, mailboxes, null));

                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(null, signer, recipients, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, null, recipients, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, signer, null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(ctx, signer, recipients, null));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(null, recipients, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(signer, null, entity));
                Assert.Throws <ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt(signer, recipients, null));

                var compressed = ApplicationPkcs7Mime.Compress(ctx, entity);
                var encrypted  = ApplicationPkcs7Mime.Encrypt(recipients, entity);
                var signed     = ApplicationPkcs7Mime.Sign(signer, entity);

                // Decompress
                Assert.Throws <ArgumentNullException> (() => compressed.Decompress(null));
                Assert.Throws <InvalidOperationException> (() => encrypted.Decompress(ctx));
                Assert.Throws <InvalidOperationException> (() => signed.Decompress(ctx));

                // Decrypt
                Assert.Throws <ArgumentNullException> (() => encrypted.Decrypt(null));
                Assert.Throws <InvalidOperationException> (() => compressed.Decrypt(ctx));
                Assert.Throws <InvalidOperationException> (() => signed.Decrypt(ctx));

                // Verify
                Assert.Throws <ArgumentNullException> (() => {
                    MimeEntity mime;

                    signed.Verify(null, out mime);
                });
                Assert.Throws <InvalidOperationException> (() => {
                    MimeEntity mime;

                    compressed.Verify(ctx, out mime);
                });
                Assert.Throws <InvalidOperationException> (() => {
                    MimeEntity mime;

                    encrypted.Verify(ctx, out mime);
                });
            }
        }