Thomas Tingsted Mathiesen RSA Encryption and VB.NET
By Thomas Tingsted Mathiesen (tma@tma.dk)
After surfing arund for a day, and finally figuring out how to use the Cryptography RSA provider in .NET.
I thought that maby others needed an easy "how to" guide.

My Linked-In profile
My company - Gaudio ApS
My FaceBook profile
Last changes made: 07 MAR 2010


Please rate this article at the bottom of this page


RSA encryption with VB.NET - www.tma.dk/rsa

Downloads

Visual Studio 2005 Solution Download
Compiled test program Download

How does RSA work

RSA works with two keys, a Private key, and a Public key.
In order for Peter to send an encrypted message to John, Peter will need Johns public key.

Lets asume that John uses the following keys:
Public key 12345
Private key 88887

Peter will then encrypt the message to John like so:
EncryptedMessage = Encrypt("Hello john","12345")

John will then be able to decrypt the message with his privatekey:
DecryptedMessage = Decrypt(EncryptedMessage,"88887")

When to use RSA and when not to.

RSA is suitable for small messages, so do not use it for encrypting files.
If you need to encrypt a file, then use another encryption for the file it self, and then encrypt and send the password for decrypting the file with RSA.

Namespaces

Imports System.Security.Cryptography

Let's code

Imports System.Security.Cryptography
Imports Encryption.RSA

private sub DoEncryption()
     Dim EncryptedData As Encryption.RSAResult = Encryption.RSA.Encrypt("Thomas Mathiesen", publicKey)
     MessageBox.Show(EncryptedData.AsBase64String, "Encrypted data")
     Dim DecryptedData As Encryption.RSAResult = Encryption.RSA.Decrypt(EncryptedData.AsBytes, privateKey)
     MessageBox.Show(DecryptedData.AsString, "Decrypted data")
End Sub

RSA class

Imports System.Security.Cryptography
Imports System.Text
Public Class RSA
    Public Shared Function Encrypt(ByVal Data As String, ByVal Publickey As String) As RSAResult
        Try
            Dim ByteConverter As New UnicodeEncoding()
            Return Encrypt(ByteConverter.GetBytes(Data), Publickey)
        Catch ex As Exception
            Throw New Exception("Encrypt(String): " & ex.Message, ex)
        End Try
    End Function

    Public Shared Function Encrypt(ByVal Data() As Byte, ByVal Publickey As String) As RSAResult
        Try
            Dim RSA As System.Security.Cryptography.RSACryptoServiceProvider = New System.Security.Cryptography.RSACryptoServiceProvider()
            RSA.FromXmlString(Publickey)
            Return New RSAResult(RSAEncrypt(Data, RSA.ExportParameters(False), False))
        Catch ex As Exception
            Throw New Exception("Encrypt(Bytes): " & ex.Message, ex)
        End Try
    End Function

    Public Shared Function Decrypt(ByVal Data() As Byte, ByVal Privatekey As String) As RSAResult
        Try
            Dim RSA As System.Security.Cryptography.RSACryptoServiceProvider = New System.Security.Cryptography.RSACryptoServiceProvider()
            RSA.FromXmlString(Privatekey)
            Dim Result As New RSAResult(RSADecrypt(Data, RSA.ExportParameters(True), False))
            Return Result
        Catch ex As Exception
            Throw New Exception("Decrypt(): " & ex.Message, ex)
        End Try
    End Function

    Private Shared Function RSAEncrypt(ByVal DataToEncrypt() As Byte, ByVal RSAKeyInfo As RSAParameters, ByVal DoOAEPPadding As Boolean) As Byte()
        Try
            Dim encryptedData() As Byte
            Using RSA As New RSACryptoServiceProvider
                RSA.ImportParameters(RSAKeyInfo)
                encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding)
            End Using
            Return encryptedData
        Catch e As CryptographicException
            Throw New Exception("RSAEncrypt(): " & e.Message, e)
        End Try
    End Function

    Private Shared Function RSADecrypt(ByVal DataToDecrypt() As Byte, ByVal RSAKeyInfo As RSAParameters, ByVal DoOAEPPadding As Boolean) As Byte()
        Try
            Dim decryptedData() As Byte
            Using RSA As New RSACryptoServiceProvider
                RSA.ImportParameters(RSAKeyInfo)
                decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding)
            End Using
            Return decryptedData
        Catch e As CryptographicException
            Throw New Exception("RSADecrypt(): " & e.Message, e)
        End Try
    End Function
End Class

RSAresult class

Imports System.Text
Public Class RSAResult
    Private _Data() As Byte
    Public Sub New(ByVal Data() As Byte)
        _Data = Data
    End Sub
    Public ReadOnly Property AsBytes() As Byte()
        Get
            Return _Data
        End Get
    End Property
    Public ReadOnly Property AsString() As String
        Get
            Dim ByteConverter As New UnicodeEncoding()
            Return ByteConverter.GetString(_Data)
        End Get
    End Property
    Public ReadOnly Property AsBase64String() As String
        Get
            Return Convert.ToBase64String(_Data)
        End Get
    End Property
End Class

Application form code

Imports System.Security.Cryptography
Imports Encryption.RSA
Public Class Form1
    Private Sub btnNewKeys_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewKeys.Click
        CreateNewKeys()
    End Sub
    Private Sub CreateNewKeys()
        Dim Keys As Encryption.Keypair = Encryption.Keypair.CreateNewKeys
        txtPrivateKey.Text = Keys.Privatekey
        txtPublicKey.Text = Keys.Publickey
    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CreateNewKeys()
    End Sub
    Private Sub EncryptMessage()
        Try
            Dim EncryptedMessage As Encryption.RSAResult = Encryption.RSA.Encrypt(txtMessageToEncrypt.Text, txtPublicKey.Text)
            Dim DecryptedMessage As Encryption.RSAResult = Encryption.RSA.Decrypt(EncryptedMessage.AsBytes, txtPrivateKey.Text)
            txtEncryptedBase64.Text = EncryptedMessage.AsBase64String
            txtDecryptedMessage.Text = DecryptedMessage.AsString
            txtErrorMessage.Text = "OK"
        Catch ex As Exception
            txtErrorMessage.Text = ex.Message
        End Try
    End Sub

    Private Sub btnEncrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEncrypt.Click
        EncryptMessage()
    End Sub
End Class

Downloads

Visual Studio 2005 Solution Download
Compiled test program Download