OpenPGP Email messages in C# and VB.NET

OpenPGP encrypted and/or signed data can be sent via email. The automated handling of such email messages is usually performed by plug-ins to the email client applications. Two of the common software applications for handling OpenPGP encrypted email messages are Symantec PGP Desktop(r) and the Enigmail plugin for Thunderbird.

There are two ways of transferring OpenPGP data within an email message: inline PGP data (in the early days of the Internet) and PGP/MIME (described in RFC 3156). In both of the formats  the email subject will remain unencrypted. Unfortunately due to limitations in the Microsoft .NET Framework email related functionality (limited MIME parses) only creation of PGP-inline messages is possible. For PGP/MIME emails handling check our plugable API designed for easy integration with third party Mail API’s for the .NET Framework.

Below you will find examples that shows how to send encrypted and signed inline OpenPGP email messages.

Table of Contents

1. Encrypted OpenPGP Email message
2. Encrypted OpenPGP Email message with attachmenet
3. Clear text signed  OpenPGP Email message


 

1. Sending an encrypted OpenPGP email message

In this example the text of the email message is loaded from a file.

The code can easily be modified to encrypt a message text available as a String variable by using the method PGPLib.EncryptString as you can see in the next example.

C# example

using System;
using System.Web;
 
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
 
using DidiSoft.Pgp;
 
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 }
 
/// Demonstrates how to send an Inline encrypted PGP mail message
protected void btnInlinePGPEncrypt_Click(object sender, EventArgs e)
{
 try
 {
  // Initialize the mail message
  MailMessage message = new MailMessage();
  MailAddress fromAddress = new MailAddress("myemail@mywebsite.com");
  message.From = fromAddress;
  message.To.Add("recipient@company.com");
  message.Subject = "Encrypted PGP Email message example";
 
  // Prepare the OpenPGP encrypted message text
  PGPLib pgp = new PGPLib();
 
  // We use ASCII armored data for emails
  bool asciiArmor = true;
 
  // Encrypt the data into a MemoryStream object
  MemoryStream encryptedText = new MemoryStream();
  using (Stream dataStream = File.OpenRead(@"c:\Temp\email_text.txt"))
  {
   using (Stream recipientKeyStream = File.OpenRead(@"C:\Keys\recipient_key.asc"))
   {
    string internalFileNameLable = "encrypted.pgp";
    pgp.EncryptStream(dataStream,
                      internalFileNameLable,
                      recipientKeyStream,
                      encryptedText,
                      asciiArmor);
   }
  }
 
   string msgBody = System.Text.Encoding.ASCII.GetString(
                     encryptedText.GetBuffer(), 0, (int)encryptedText.Length);
 
   // the actual Email message text is set as an AlternateView in
   // order to preserve the line endings, but it can be set also as a Body
   AlternateView encryptedView = 
         AlternateView.CreateAlternateViewFromString(msgBody,
                     new ContentType("text/plain; charset=ISO-8859-1"));
   encryptedView.TransferEncoding = TransferEncoding.SevenBit;
 
   message.BodyEncoding = Encoding.ASCII;
   message.IsBodyHtml = false;
   message.Body = null;
   message.AlternateViews.Add(encryptedView);
 
   // Send the message
   SmtpClient smtpClient = new SmtpClient();
   smtpClient.Host = "mail.mywebsite.org";
   smtpClient.UseDefaultCredentials = true;
   smtpClient.Send(message);
 
   Response.Write( "Mail sent" );
  }
  catch (Exception ex)
  {
   Response.Write( ex.Message );
  }
 }
}
}

VB.NET example

Imports System
Imports System.Web
 
Imports System.Text
Imports System.IO
Imports System.Net.Mail
Imports System.Net.Mime
 
Imports DidiSoft.Pgp
 
Namespace WebApplication1
 
Public Partial Class _Default
   Inherits System.Web.UI.Page
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
 End Sub
 
 ''' Demonstrates how to send an Inline encrypted PGP mail message 
 Protected Sub btnInlinePGPEncrypt_Click(ByVal s As Object, ByVal e As EventArgs)
  Try
   ' Initialize the mail message
   Dim message As New MailMessage()
   Dim fromAddress As New MailAddress("mail2@netftp.org")
   message.From = fromAddress
   message.[To].Add("mail1@netftp.org")
   message.Subject = "Encrypted PGP Email message example"
 
   ' Prepare the OpenPGP encrypted message text
   Dim pgp As New PGPLib()
 
   ' We use ASCII armored data for emails
   Dim asciiArmor As Boolean = True
   ' Encrypt the data into a MemoryStream object
   Dim encryptedText As New MemoryStream()
   Using dataStream As Stream = File.OpenRead("c:\Temp\email_text.txt")
   Using recipientKeyStream As Stream = File.OpenRead("C:\Keys\recipient_key.asc")
    Dim internalFileNameLable As String = "encrypted.pgp"
    pgp.EncryptStream(dataStream, internalFileNameLable, _
                     recipientKeyStream, _
                     encryptedText, _
                     asciiArmor)
   End Using
  End Using
 
  Dim msgBody As String = _
   System.Text.Encoding.ASCII.GetString(encryptedText.GetBuffer(), 0, _
                                        CInt(encryptedText.Length))
 
   ' the actual Email message text is set as an AlternateView in
   ' order to preserve the line endings, but it can be set also as a Body
   Dim encryptedView As AlternateView = _
               AlternateView.CreateAlternateViewFromString(msgBody, _
                            New ContentType("text/plain; charset=ISO-8859-1"))
   encryptedView.TransferEncoding = TransferEncoding.SevenBit
 
   message.BodyEncoding = Encoding.ASCII
   message.IsBodyHtml = False
   message.Body = Nothing
   message.AlternateViews.Add(encryptedView)
 
   ' Send the message
   Dim smtpClient As New SmtpClient()
   smtpClient.Host = "mail.mywebsite.com"
   smtpClient.UseDefaultCredentials = True
   smtpClient.Send(message)
 
   Response.Write("Mail sent")
  Catch ex As Exception
   Response.Write(ex.Message)
  End Try
 End Sub
End Class
End Namespace

Back to Top

2. Encrypted OpenPGP Email message with attachmenet

Adding an additional encrypted attachment is straightforward just like adding a standard attachment. Please check the example below for details:

C# example

using System;
using System.Web;
 
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
 
using DidiSoft.Pgp;
 
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 }
 
 // Demonstrates how to send an Inline encrypted PGP mail message
 protected void btnInlinePGPEncryptWithAttachment_Click(object sender, EventArgs e)
 {
  try
  {
   // Initialize the mail message
   MailMessage message = new MailMessage();
   MailAddress fromAddress = new MailAddress("myemail@mysite.com");
   message.From = fromAddress;
   message.To.Add("recipient@company.com");
   message.Subject = "Encrypted PGP Email message with attachment";
 
   // Prepare the OpenPGP encrypted message text
   PGPLib pgp = new PGPLib();
 
   string messageUnencrypted = "This is the email message body";
   string msgBody = pgp.EncryptString(messageUnencrypted,
                                      @"C:\Keys\recipient_key.asc");
 
   // the actual Email message text is set as an AlternateView in
   // order to preserve the line endings, but it can be set also as a Body
   AlternateView encryptedView = 
             AlternateView.CreateAlternateViewFromString(msgBody, 
                         new ContentType("text/plain; charset=ISO-8859-1"));
   encryptedView.TransferEncoding = TransferEncoding.SevenBit;
 
   message.BodyEncoding = Encoding.ASCII;
   message.IsBodyHtml = false;
   message.Body = null;
   message.AlternateViews.Add(encryptedView);
 
   // We use ASCII armored data for emails
   bool asciiArmor = true;
   // Encrypted attachment
   pgp.EncryptFile(@"c:\Files\data.doc", 
                  @"C:\Keys\recipient_key.asc", 
                  @"c:\Temp\encrypted.pgp", 
                  asciiArmor);
   Attachment attachedEncryptedFile = new Attachment(@"c:\Temp\encrypted.pgp");
   attachedEncryptedFile.TransferEncoding = TransferEncoding.Base64;
   message.Attachments.Add(attachedEncryptedFile);
 
   // Send the message
   SmtpClient smtpClient = new SmtpClient();
   smtpClient.Host = "mail.netftp.org";
   smtpClient.UseDefaultCredentials = true;
   smtpClient.Send(message);
 
   Response.Write("Mail sent");
  }
  catch (Exception ex)
  {
   Response.Write(ex.Message);
  }
 }
}
}

VB.NET example

Imports System
Imports System.Web
 
Imports System.Text
Imports System.IO
Imports System.Net.Mail
Imports System.Net.Mime
 
Imports DidiSoft.Pgp
 
Namespace WebApplication1
 
Public Partial Class _Default
   Inherits System.Web.UI.Page
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
 End Sub
 
 ''' Demonstrates how to send an Inline encrypted PGP mail message
 Protected Sub btnInlinePGPEncryptWithAttachment_Click(ByVal sender As Object, _
                                                       ByVal e As EventArgs)
  Try
   ' Initialize the mail message
   Dim message As New MailMessage()
   Dim fromAddress As New MailAddress("myemail@mysite.com")
   message.From = fromAddress
   message.[To].Add("recipient@company.com")
   message.Subject = "Encrypted PGP Email message with attachment example"
 
   ' Prepare the OpenPGP encrypted message text
   Dim pgp As New PGPLib()
 
   Dim messageUnencrypted As String = "This is the email message body"
   Dim msgBody As String = pgp.EncryptString(messageUnencrypted, _
                                        "C:\Keys\recipient_key.asc")
 
   ' the actual Email message text is set as an AlternateView in
   ' order to preserve the line endings, but it can be set also as a Body
   Dim encryptedView As AlternateView = _
            AlternateView.CreateAlternateViewFromString(msgBody, _
                      New ContentType("text/plain; charset=ISO-8859-1"))
   encryptedView.TransferEncoding = TransferEncoding.SevenBit
 
   message.BodyEncoding = Encoding.ASCII
   message.IsBodyHtml = False
   message.Body = Nothing
   message.AlternateViews.Add(encryptedView)
 
   ' We use ASCII armored data for emails
   Dim asciiArmor As Boolean = True
   ' Encrypted attachment
   pgp.EncryptFile("c:\Files\data.doc", "C:\Keys\recipient_key.asc", _
                   "c:\Temp\encrypted.pgp", _
                   asciiArmor)
   Dim attachedEncryptedFile As New Attachment("c:\Temp\encrypted.pgp")
   attachedEncryptedFile.TransferEncoding = TransferEncoding.Base64
   message.Attachments.Add(attachedEncryptedFile)
 
   ' Send the message
   Dim smtpClient As New SmtpClient()
   smtpClient.Host = "mail.netftp.org"
   smtpClient.UseDefaultCredentials = True
   smtpClient.Send(message)
 
   Response.Write("Mail sent")
  Catch ex As Exception
   Response.Write(ex.Message)
  End Try
 End Sub
End Class
End Namespace

Back to Top

3. Sending a clear text signed  OpenPGP email message

The idea behind the clear text signed email messages is that the message authenticity can be verified through a digital signature and a recipient that does not possess an OpenPGP software can still read the message text.

C# example

using System;
using System.Web;
 
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
 
using DidiSoft.Pgp;
 
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 }
 
 /// Demonstrates how to send a clear text signed PGP mail message
 protected void btnInlinePGPSignature_Click(object sender, EventArgs e)
 {
  try
  {
   // Initialize the mail message
   MailMessage message = new MailMessage();
   MailAddress fromAddress = new MailAddress("myemail@mysite.com");
   message.From = fromAddress;
   message.To.Add("recipient@company.com");
   message.Subject = "Clear signed PGP Email message example";
 
   // Prepare the OpenPGP encrypted message text
   PGPLib pgp = new PGPLib();
 
   string messageText = "This is the email text";
   string myPrivateKeyPassword = "my password";
   string messageTextSigned = 
     pgp.ClearSignString(messageText, 
                         @"C:\keys\my_private_key.asc", 
                         myPrivateKeyPassword, 
                         HashAlgorithm.SHA1);
 
   string msgBody = messageTextSigned;
 
   // the actual Email message text is set as an AlternateView in
   // order to preserve the line endings, but it can be set also as a Body
   AlternateView signedView = AlternateView.CreateAlternateViewFromString(msgBody, 
                        new ContentType("text/plain; charset=ISO-8859-1"));
   signedView.TransferEncoding = TransferEncoding.SevenBit;
 
   message.BodyEncoding = Encoding.ASCII;
   message.IsBodyHtml = false;
   message.Body = null;
   message.AlternateViews.Add(signedView);
 
   // Send the message
   SmtpClient smtpClient = new SmtpClient();
   smtpClient.Host = "mail.mysite.com";
   smtpClient.UseDefaultCredentials = true;
   smtpClient.Send(message);
 
   Response.Write("Mail sent");
  }
  catch (Exception ex)
  {
   Response.Write(ex.Message);
  }
 }
}
}

VB.NET

 ''' Demonstrates how to send an Inline clear text signed PGP mail message
 Protected Sub btnInlinePGPSignature_Click(ByVal sender As Object, ByVal e As EventArgs)
  Try
   ' Initialize the mail message
   Dim message As New MailMessage()
   Dim fromAddress As New MailAddress("myemail@mysite.com")
   message.From = fromAddress
   message.[To].Add("recipient@company.com")
   message.Subject = "Clear signed PGP Email message example"
 
   ' Prepare the OpenPGP encrypted message text
   Dim pgp As New PGPLib()
 
   Dim messageText As String = "This is the email text"
   Dim myPrivateKeyPassword As String = "my password"
   Dim messageTextSigned As String = _
     pgp.ClearSignString(messageText, _
                         "C:\Keys\recipient_key.asc", _
                         myPrivateKeyPassword, _
                         HashAlgorithm.SHA1)
 
   Dim msgBody As String = messageTextSigned
 
   ' the actual Email message text is set as an AlternateView in
   ' order to preserve the line endings, but it can be set also as a Body
   Dim signedView As AlternateView = _
      AlternateView.CreateAlternateViewFromString(msgBody, _
                     New ContentType("text/plain; charset=ISO-8859-1"))
   signedView.TransferEncoding = TransferEncoding.SevenBit
 
   message.BodyEncoding = Encoding.ASCII
   message.IsBodyHtml = False
   message.Body = Nothing
   message.AlternateViews.Add(signedView)
 
   ' Send the message
   Dim smtpClient As New SmtpClient()
   smtpClient.Host = "mail.mysite.com"
   smtpClient.UseDefaultCredentials = True
   smtpClient.Send(message)
 
   Response.Write("Mail sent")
  Catch ex As Exception
   Response.Write(ex.Message)
  End Try
 End Sub
End Class
End Namespace

Back to Top

Summary

In this chapter we have shown how to send OpenPGP encrypted and clear text signed email messages with the help of the System.Net.Mail classes.