Friday, March 11, 2011

3DES Encryptor sample in VB.NET

Hi All,

Welcome to my blog again. I had a requirement in my project to encrypt some settings using a simple encryption. But I couldn't find a ready made solution, and from my college days, I always liked 3DES encryption. So, here is a "ready made" solution :

{Note: Of course, you'll have to change the IV (initialization vector) and the Key in the variable strCrypt }

Imports System.Security.Cryptography
Imports System.IO
Public Class clsDCrypto

    Private m_bKey(), m_bIV() As Byte

    Public Sub New()
        Dim strCrypt, strIV As String
        strCrypt = "q5AsCA64SeY+SpoJ24ERrg=="
        strIV = "VaOHJOI2J/c="
        m_bKey = Convert.FromBase64String(strCrypt)
        m_bIV = Convert.FromBase64String(strIV)
    End Sub

    Public Function DecryptString(ByVal strCipherText As String) As String
        Dim strTempDecrypt As String
        Dim memstream2 As New MemoryStream
        Dim iCryptoDecryptor As ICryptoTransform
        Dim tDESProviderd As New TripleDESCryptoServiceProvider
        Dim cryptdStream As CryptoStream
        Dim bCipher As Byte()

        bCipher = Convert.FromBase64String(strCipherText)
        tDESProviderd.KeySize = 128
        iCryptoDecryptor = tDESProviderd.CreateDecryptor(m_bKey, m_bIV)
        cryptdStream = New CryptoStream(memstream2, iCryptoDecryptor, CryptoStreamMode.Write)
        cryptdStream.Write(bCipher, 0, bCipher.Length)
        memstream2.Position = 0

        Dim temp2(CType(memstream2.Length - 1, System.Int32)) As Byte

        memstream2.Read(temp2, 0, CType(temp2.Length, System.Int32))

        strTempDecrypt = System.Text.Encoding.UTF8.GetString(temp2)
        Return strTempDecrypt
    End Function

    Public Function EncryptString(ByVal strPlainText As String) As String

        Dim tDESProvider As New TripleDESCryptoServiceProvider
        'Dim tDes2 As New TripleDES
        Dim cryptStream As CryptoStream
        Dim iCryptoEncryptor As ICryptoTransform
        Dim memStream As New MemoryStream()
        Dim bPlainText As Byte()
        Dim strTempEncrypt As String

        tDESProvider.KeySize = 128

        iCryptoEncryptor = tDESProvider.CreateEncryptor(m_bKey, m_bIV)
        cryptStream = New CryptoStream(memStream, iCryptoEncryptor, CryptoStreamMode.Write)
        bPlainText = System.Text.Encoding.UTF8.GetBytes(strPlainText)
        cryptStream.Write(bPlainText, 0, bPlainText.Length)
        Dim tmp(CType(memStream.Length - 1, System.Int32)) As Byte
        memStream.Position = 0
        memStream.Read(tmp, 0, CType(memStream.Length, System.Int32))
        strTempEncrypt = Convert.ToBase64String(tmp)
        Return strTempEncrypt
    End Function
End Class

No comments: