Sunday, October 4, 2009

Encrypt/Decrypt Text in VB.NET

In this article I have code which can be used encrypt the text before saving it in the file, database, registry, etc to protect from misuse. There are many article we can find on internet to encrypt/decrypt text in .Net. Each have different ways for encryption with some having very long code. So I have created a  very simple two functions to encrypt/decrypt a text in .Net. Both the functions contains two parameter. First parameter “Text” will be the text which need to encrypted and second parameter is “Key” which is a private key which will help identity during decrypt. So key during decrypt should be same as in encypt to decrypt the text correctly.

Code to encrypt the Text

 

Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Function Encrypt(ByVal text As String, ByVal key As String) As String
Try
Dim crp As New TripleDESCryptoServiceProvider
Dim uEncode As New UnicodeEncoding
Dim bytPlainText() As Byte = uEncode.GetBytes(text)
Dim stmCipherText As New MemoryStream
Dim slt() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Dim pdb As New Rfc2898DeriveBytes(key, slt)
Dim bytDerivedKey() As Byte = pdb.GetBytes(24)

crp.Key = bytDerivedKey
crp.IV = pdb.GetBytes(8)

Dim csEncrypted As New CryptoStream(stmCipherText, crp.CreateEncryptor(), CryptoStreamMode.Write)

csEncrypted.Write(bytPlainText, 0, bytPlainText.Length)
csEncrypted.FlushFinalBlock()
Return Convert.ToBase64String(stmCipherText.ToArray())
Catch ex As Exception
Throw
End Try
End Function

So for example Encrypt(“Demo”, “12345″) will return 1T5yxecmgLbsxQu4iQx5Bg==”


Code to decrypt the Text

Function Decrypt(ByVal text As String, ByVal key As String) As String
Dim crp As TripleDESCryptoServiceProvider
Try
crp = New TripleDESCryptoServiceProvider
Dim uEncode As New UnicodeEncoding
Dim bytCipherText() As Byte = Convert.FromBase64String(text)
Dim stmPlainText As New MemoryStream
Dim stmCipherText As New MemoryStream(bytCipherText)
Dim slt() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Dim pdb As New Rfc2898DeriveBytes(key, slt)
Dim bytDerivedKey() As Byte = pdb.GetBytes(24)
crp.Key = bytDerivedKey
crp.IV = pdb.GetBytes(8)

Dim csDecrypted As New CryptoStream(stmCipherText, crp.CreateDecryptor(), CryptoStreamMode.Read)
Dim sw As New StreamWriter(stmPlainText)
Dim sr As New StreamReader(csDecrypted)
sw.Write(sr.ReadToEnd)
sw.Flush()
csDecrypted.Clear()
crp.Clear()
Return uEncode.GetString(stmPlainText.ToArray())
Catch ex As Exception
Throw
End Try
End Function

So now when we decrypt the text encrypted above we will get the required text

So Decrypt(“1T5yxecmgLbsxQu4iQx5Bg==”, “12345″) will return “Demo”

No comments:

Post a Comment