VB.NET - Sign email (RSASSA-PSS + SHA256) and encrypt email (RSAES-OAEP + AES 128/196/256 + SHA256) based on EDIFACT rule - S/MIME

The following VB.NET example codes demonstrate how to sign email to S/MIME format with digital signature (RSASSA-PSS + SHA256) and how to encrypt email with RSAES-OAEP + AES 128/192/256 + SHA256.

EDIFACT rule in EUROPE

Latest EDIFACT requires RSA-SHA256 Signature Algorithm + RSASSA-PSS with SHA256 padding for digital signature, and AES128/192/256 Encrypting Algorithm + RSAES-OAEP + SHA256 Hash for email encryption.

EASendMail uses Windows/.NET built-in function to implement S/MIME, it supports RSASSA-PSS signature + SHA1 padding and AES + RSAES-OAEP, however it has a compatible problem with RSASSA-PSS signature defined in latest EDIFACT (SHA256 padding).

To comply with EDIFACT rule, we implemented a special version with Bouncy Castle library.

EASendMail with Bouncy Castle

If you need to sign email with digital signature or encrypt email based on the rule of EDIFACT in EUROPE, you should use this version:

You can download it from: http://www.emailarchitect.net/webapp/download/easendmail.bc.exe

To use it in your project, the first step is Add reference of EASendMail BC to your project. Please create or open your project with Visual Studio, then go to menu -> Project -> Add Reference -> .NET -> Browse..., and select Installation Path\Lib\net[version]\EASendMail.dll from your disk, click Open -> OK.

The default Installation path is C:\Program Files (x86)\EASendMail.BC\

You can also install the run-time assembly by NuGet. Run the following command in the NuGet Package Manager Console:

Install-Package EASendMail.BC

VB.NET - Sign email with RSASSA-PSS + SHA256 - EDIFACT - S/MIME - example

The following example codes demonstrate signing email based on EDIFACT rule - S/MIME. In order to run it correctly, please change SMTP server, user, password, sender, recipient value to yours.

Imports System.Security.Cryptography.X509Certificates
' Add EASendMail namespace
Imports EASendMail

Module Module1
    Private Function _findCertificate(storeName As String, emailAddress As String) As X509Certificate2

        Dim cert As X509Certificate2 = Nothing
        Dim store As New X509Store(storeName, StoreLocation.CurrentUser)

        store.Open(OpenFlags.ReadOnly)
        Dim certfiicates As X509Certificate2Collection = store.Certificates.Find(X509FindType.FindBySubjectName, emailAddress, True)
        If certfiicates.Count > 0 Then
            cert = certfiicates(0)
        End If

        store.Close()

        _findCertificate = cert
    End Function

    Sub Main()

        Try
            Dim oMail As New SmtpMail("TryIt")

            ' Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net"

            ' Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net"

            ' Set email subject
            oMail.Subject = "test email from vb.net with digital signature"

            ' Set email body
            oMail.TextBody = "this is a test email with digital signature based on EDIFACT rule (S/MIME)"

            ' Digital signature with sha256 hash algorithm + RSASSA-PSS signature + sha256 padding
            oMail.SignatureHashAlgorithm = SignatureHashAlgorithmType.SHA256
            oMail.SignatureHashEncryption = SignatureHashEncryptionType.RSA_SSA_PSS_WITH_PARAMETER

            ' Search certificate based on email address.
            Dim signerCertificate As X509Certificate2 = _findCertificate("My", oMail.From.Address)
            If signerCertificate Is Nothing Then
                Throw New Exception("No signer certificate found for " + oMail.From.Address + "!")
            End If

            oMail.From.Certificate2 = signerCertificate
            ' You can also load the signer certificate from a pfx file.
            '
            ' Dim pfxPath As String = "D:\TestCerts\signer.pfx"
            ' Dim signerCertFromPfx As X509Certificate2 = New X509Certificate2(pfxPath,
            '        "nosecret",
            ' X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.UserKeySet)
            ' oMail.From.Certificate2 = signerCertFromPfx

            ' If you use it in web application,
            ' please use  X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.MachineKeySet

            ' If you use it in .NET core application
            ' please use X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.EphemeralKeySet

            ' Your SMTP server address
            Dim oServer As New SmtpServer("smtp.emailarchitect.net")

            ' User and password for ESMTP authentication, if your server doesn't require
            ' User authentication, please remove the following codes.
            oServer.User = "test@emailarchitect.net"
            oServer.Password = "testpassword"

            ' Most mordern SMTP servers require SSL/TLS connection now.
            ' ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
            oServer.ConnectType = SmtpConnectType.ConnectTryTLS

            ' If your SMTP server uses 587 port
            ' oServer.Port = 587

            ' If your SMTP server requires SSL/TLS connection on 25/587/465 port
            ' oServer.Port = 25 ' 25 or 587 or 465
            ' oServer.ConnectType = SmtpConnectType.ConnectSSLAuto

            Console.WriteLine("start to send email ...")

            Dim oSmtp As New SmtpClient()
            oSmtp.SendMail(oServer, oMail)

            Console.WriteLine("email was sent successfully!")

        Catch ep As Exception

            Console.WriteLine("failed to send email with the following error:")
            Console.WriteLine(ep.Message)
        End Try

    End Sub

End Module

Note

RSASSA-PSS signature generated by Bouncy Castle is not verified by most email clients (outlook, firebird …), but it does meet the requirement in EDIFACT rule.

VB.NET - Encrypt email with RRSAES-OAEP + AES 128/192/256 + SHA256 - EDIFACT - S/MIME - example

The following example codes demonstrate encrypting email message based on EDIFACT rule - S/MIME. In order to run it correctly, please change SMTP server, user, password, sender, recipient value to yours.

Imports System.Security.Cryptography.X509Certificates
' Add EASendMail namespace
Imports EASendMail

Module Module1

    Private Function _findCertificate(storeName As String, emailAddress As String) As X509Certificate2

        Dim cert As X509Certificate2 = Nothing
        Dim store As New X509Store(storeName, StoreLocation.CurrentUser)

        store.Open(OpenFlags.ReadOnly)
        Dim certfiicates As X509Certificate2Collection = store.Certificates.Find(X509FindType.FindBySubjectName, emailAddress, True)
        If certfiicates.Count > 0 Then
            cert = certfiicates(0)
        End If

        store.Close()

        _findCertificate = cert
    End Function

    Sub Main()

        Try
            Dim oMail As New SmtpMail("TryIt")

            ' Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net"

            ' Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net"

            ' Set email subject
            oMail.Subject = "test encrypted email from vb.net"

            ' Set email body
            oMail.TextBody = "this is a test encrypted email based on EDIFACT rule (S/MIME)"

            ' Email encryption with RAES-OAEP-128 + sha-256 oaep hash algorithm
            oMail.EncryptionAlgorithm = EncryptionAlgorithmType.RAES_OAEP_128
            ' RAES_OAEP_128 uses AES128, you can also use  RAES_OAEP_192 (AES192) and RAES_OAEP_256 (AES256)
            oMail.OaepHashAlgorithm = OaepHashAlgorithmType.SHA256

            Dim count As Integer = oMail.To.Count
            For i As Integer = 0 To count - 1
                Dim oAddress As MailAddress = oMail.To(i)

                Dim encryptCert As X509Certificate2 = _findCertificate("AddressBook", oAddress.Address)
                If encryptCert Is Nothing Then
                    encryptCert = _findCertificate("My", oAddress.Address)
                End If

                If encryptCert Is Nothing Then
                    Throw New Exception("No encryption certificate found for " + oAddress.Address + "!")
                End If

                oAddress.Certificate2 = encryptCert

                ' You can also load the encryptor certificate from a cer file Like this

                ' Dim cerPath As String = "D:\TestCerts\encryptor.cer"
                ' Dim encryptCertFromFile = New X509Certificate2(cerPath)
                ' oAddress.Certificate2 = encryptCertFromFile
            Next

            ' Your SMTP server address
            Dim oServer As New SmtpServer("smtp.emailarchitect.net")

            ' User and password for ESMTP authentication, if your server doesn't require
            ' User authentication, please remove the following codes.
            oServer.User = "test@emailarchitect.net"
            oServer.Password = "testpassword"

            ' Most mordern SMTP servers require SSL/TLS connection now.
            ' ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
            oServer.ConnectType = SmtpConnectType.ConnectTryTLS

            ' If your SMTP server uses 587 port
            ' oServer.Port = 587

            ' If your SMTP server requires SSL/TLS connection on 25/587/465 port
            ' oServer.Port = 25 ' 25 or 587 or 465
            ' oServer.ConnectType = SmtpConnectType.ConnectSSLAuto

            Console.WriteLine("start to send encrypted email ...")

            Dim oSmtp As New SmtpClient()
            oSmtp.SendMail(oServer, oMail)

            Console.WriteLine("email was sent successfully!")

        Catch ep As Exception

            Console.WriteLine("failed to send email with the following error:")
            Console.WriteLine(ep.Message)
        End Try

    End Sub

End Module

VB.NET - Sign email with RSASSA-PSS + SHA256 and encrypt email with RRSAES-OAEP + AES 128/192/256 + SHA256 - EDIFACT - S/MIME - example

The following example codes demonstrate signing and encrypting email message based on EDIFACT rule - S/MIME. In order to run it correctly, please change SMTP server, user, password, sender, recipient value to yours.

Imports System.Security.Cryptography.X509Certificates
' Add EASendMail namespace
Imports EASendMail

Module Module1

    Private Function _findCertificate(storeName As String, emailAddress As String) As X509Certificate2

        Dim cert As X509Certificate2 = Nothing
        Dim store As New X509Store(storeName, StoreLocation.CurrentUser)

        store.Open(OpenFlags.ReadOnly)
        Dim certfiicates As X509Certificate2Collection = store.Certificates.Find(X509FindType.FindBySubjectName, emailAddress, True)
        If certfiicates.Count > 0 Then
            cert = certfiicates(0)
        End If

        store.Close()

        _findCertificate = cert
    End Function

    Sub Main()

        Try
            Dim oMail As New SmtpMail("TryIt")

            ' Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net"

            ' Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net"

            ' Set email subject
            oMail.Subject = "test signed and encrypted email from vb.net"

            ' Set email body
            oMail.TextBody = "this is a test signed and encrypted email based on EDIFACT rule (S/MIME)"

            ' Digital signature with sha256 hash algorithm + RSASSA-PSS signature + sha256 padding
            oMail.SignatureHashAlgorithm = SignatureHashAlgorithmType.SHA256
            oMail.SignatureHashEncryption = SignatureHashEncryptionType.RSA_SSA_PSS_WITH_PARAMETER

            ' Search certificate based on email address.
            Dim signerCertificate As X509Certificate2 = _findCertificate("My", oMail.From.Address)
            If signerCertificate Is Nothing Then
                Throw New Exception("No signer certificate found for " + oMail.From.Address + "!")
            End If

            oMail.From.Certificate2 = signerCertificate
            ' You can also load the signer certificate from a pfx file.
            '
            ' Dim pfxPath As String = "D:\TestCerts\signer.pfx"
            ' Dim signerCertFromPfx As X509Certificate2 = New X509Certificate2(pfxPath,
            '        "nosecret",
            ' X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.UserKeySet)
            ' oMail.From.Certificate2 = signerCertFromPfx

            ' If you use it in web application,
            ' please use  X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.MachineKeySet

            ' If you use it in .NET core application
            ' please use X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.EphemeralKeySet

            ' Email encryption with RAES-OAEP-128 + sha-256 oaep hash algorithm
            oMail.EncryptionAlgorithm = EncryptionAlgorithmType.RAES_OAEP_128
            ' RAES_OAEP_128 uses AES128, you can also use  RAES_OAEP_192 (AES192) and RAES_OAEP_256 (AES256)
            oMail.OaepHashAlgorithm = OaepHashAlgorithmType.SHA256

            Dim count As Integer = oMail.To.Count
            For i As Integer = 0 To count - 1
                Dim oAddress As MailAddress = oMail.To(i)

                Dim encryptCert As X509Certificate2 = _findCertificate("AddressBook", oAddress.Address)
                If encryptCert Is Nothing Then
                    encryptCert = _findCertificate("My", oAddress.Address)
                End If

                If encryptCert Is Nothing Then
                    Throw New Exception("No encryption certificate found for " + oAddress.Address + "!")
                End If

                oAddress.Certificate2 = encryptCert

                ' You can also load the encryptor certificate from a cer file Like this

                ' Dim cerPath As String = "D:\TestCerts\encryptor.cer"
                ' Dim encryptCertFromFile = New X509Certificate2(cerPath)
                ' oAddress.Certificate2 = encryptCertFromFile
            Next

            ' Your SMTP server address
            Dim oServer As New SmtpServer("smtp.emailarchitect.net")

            ' User and password for ESMTP authentication, if your server doesn't require
            ' User authentication, please remove the following codes.
            oServer.User = "test@emailarchitect.net"
            oServer.Password = "testpassword"

            ' Most mordern SMTP servers require SSL/TLS connection now.
            ' ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
            oServer.ConnectType = SmtpConnectType.ConnectTryTLS

            ' If your SMTP server uses 587 port
            ' oServer.Port = 587

            ' If your SMTP server requires SSL/TLS connection on 25/587/465 port
            ' oServer.Port = 25 ' 25 or 587 or 465
            ' oServer.ConnectType = SmtpConnectType.ConnectSSLAuto

            Console.WriteLine("start to send encrypted email ...")

            Dim oSmtp As New SmtpClient()
            oSmtp.SendMail(oServer, oMail)

            Console.WriteLine("email was sent successfully!")

        Catch ep As Exception

            Console.WriteLine("failed to send email with the following error:")
            Console.WriteLine(ep.Message)
        End Try

    End Sub

End Module

TLS 1.2 protocol

TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.