MimeKit.MimeMessage.Encrypt C# (CSharp) Method

Encrypt() public method

Encrypt the message to the sender and all of the recipients using the specified cryptography context.
If either of the Resent-Sender or Resent-From headers are set, then the message will be encrypted to all of the addresses specified in the Resent headers (Resent-Sender, Resent-From, Resent-To, Resent-Cc, and Resent-Bcc), otherwise the message will be encrypted to all of the addresses specified in the standard address headers (Sender, From, To, Cc, and Bcc).
/// is null. /// /// An unknown type of cryptography context was used. /// /// The has not been set. /// -or- /// No recipients have been specified. /// /// A certificate could not be found for one or more of the recipients. /// /// The public key could not be found for one or more of the recipients. ///
public Encrypt ( MimeKit.Cryptography.CryptographyContext ctx ) : void
ctx MimeKit.Cryptography.CryptographyContext The cryptography context.
return void
		public void Encrypt (CryptographyContext ctx)
		{
			if (ctx == null)
				throw new ArgumentNullException (nameof (ctx));

			if (Body == null)
				throw new InvalidOperationException ("No message body has been set.");

			var recipients = GetMessageRecipients (true);
			if (recipients.Count == 0)
				throw new InvalidOperationException ("No recipients have been set.");

			if (ctx is SecureMimeContext) {
				Body = ApplicationPkcs7Mime.Encrypt ((SecureMimeContext) ctx, recipients, Body);
			} else if (ctx is OpenPgpContext) {
				Body = MultipartEncrypted.Encrypt ((OpenPgpContext) ctx, recipients, Body);
			} else {
				throw new ArgumentException ("Unknown type of cryptography context.", nameof (ctx));
			}
		}

Usage Example

Example #1
0
		public void TestMimeMessageEncrypt ()
		{
			var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
			var self = new SecureMailboxAddress ("MimeKit UnitTests", "*****@*****.**", "44CD48EEC90D8849961F36BA50DCD107AB0821A2");
			var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };

			message.From.Add (self);
			message.To.Add (self);
			message.Body = body;

			using (var ctx = new DummyOpenPgpContext ()) {
				message.Encrypt (ctx);

				Assert.IsInstanceOf<MultipartEncrypted> (message.Body);

				var encrypted = (MultipartEncrypted) message.Body;

				//using (var file = File.Create ("pgp-encrypted.asc"))
				//	encrypted.WriteTo (file);

				var decrypted = encrypted.Decrypt (ctx);

				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.");
			}
		}
All Usage Examples Of MimeKit.MimeMessage::Encrypt