How to use symmetric encryption in ASP.NET in VB.NET

If you have to use Symmetric Encryption in your ASP.NET project you can use the class described in the article How to create symmetric encryption utility class in ASP.NET in VB.NET. To illustrate this you can create a page that permits you to generate a key and enter clear-text data through a text box. You can output the encrypted data through Convert.ToBase64String(). For decryption you should call Convert.FromBase64String() to get the encrypted bytes back and pass them into the DecryptData method.

Imports System

Imports System.IO

Imports System.Text

Imports System.Security.Cryptography

Public Class Symmetric

Inherits System.Web.UI.Page

 

Private KeyFileName As String

Private AlgorithmName As String = “RC2”

 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

SymmetricEncryptionUtility.AlgorithmName = AlgorithmName

KeyFileName = Server.MapPath(“./”) & “\symmetric_key.config”

End Sub

 

Protected Sub GenerateKeyCommand_Click(sender As Object, e As EventArgs) Handles GenerateKeyCommand.Click

SymmetricEncryptionUtility.ProtectKey = EncryptKeyCheck.Checked

SymmetricEncryptionUtility.GenerateKey(KeyFileName)

Response.Write(“Key generated successfully!”)

End Sub

 

Protected Sub EncryptCommand_Click(sender As Object, e As EventArgs) Handles EncryptCommand.Click

‘ Check for encryption key

If Not File.Exists(KeyFileName) Then

Response.Write(“Missing encryption key. Please generate key!”)

End If

Dim data As Byte() = SymmetricEncryptionUtility.EncryptData(ClearDataText.Text, KeyFileName)

EncryptedDataText.Text = Convert.ToBase64String(data)

End Sub

 

Protected Sub DecryptCommand_Click(sender As Object, e As EventArgs) Handles DecryptCommand.Click

‘ Check for encryption key

If Not File.Exists(KeyFileName) Then

Response.Write(“Missing encryption key. Please generate key!”)

End If

Dim data As Byte() = Convert.FromBase64String(EncryptedDataText.Text)

ClearDataText.Text = SymmetricEncryptionUtility.DecryptData(data, KeyFileName)

End Sub

 

Protected Sub ClearCommand_Click(sender As Object, e As EventArgs) Handles ClearCommand.Click

EncryptedDataText.Text = “”

ClearDataText.Text = “”

End Sub

End Class

 

The next picture presents the results:

 

The resulting web page for symmetric algorithms in VB.NET

The resulting web page for symmetric algorithms in VB.NET