Tips and tricks for .NET using ASP and VB code.

Encrypt or Decript text with password

    Public PublicKey() As Byte = {}
    Public PublicIv() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Public PublicEncryptionKey As String = "PassWord"

    Function Decrypt(ByVal TextToDecrypt As String) As String
        Dim TextToDecryptByteArray(TextToDecrypt.Length) As Byte
        PublicKey = System.Text.Encoding.UTF8.GetBytes(Left(PublicEncryptionKey, 8))
        Dim DataEncryptionStandard As New System.Security.Cryptography.DESCryptoServiceProvider
        TextToDecryptByteArray = Convert.FromBase64String(TextToDecrypt)
        Dim TextMemoryStream As New IO.MemoryStream
        Dim TextCryptoStream As New System.Security.Cryptography.CryptoStream(TextMemoryStream, DataEncryptionStandard.CreateDecryptor(PublicKey, PublicIv), System.Security.Cryptography.CryptoStreamMode.Write)
        TextCryptoStream.Write(TextToDecryptByteArray, 0, TextToDecryptByteArray.Length)
        TextCryptoStream.FlushFinalBlock()
        Dim Utf8Encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return Utf8Encoding.GetString(TextMemoryStream.ToArray())
    End Function

    Function Encrypt(ByVal TextToEncrypt As String) As String
        PublicKey = System.Text.Encoding.UTF8.GetBytes(Left(PublicEncryptionKey, 8))
        Dim DataEncryptionStandard As New System.Security.Cryptography.DESCryptoServiceProvider
        Dim TextToEncryptByteArray() As Byte = Encoding.UTF8.GetBytes(TextToEncrypt)
        Dim TextMemoryStream As New IO.MemoryStream
        Dim TextCryptoStream As New System.Security.Cryptography.CryptoStream(TextMemoryStream, DataEncryptionStandard.CreateEncryptor(PublicKey, PublicIv), System.Security.Cryptography.CryptoStreamMode.Write)
        TextCryptoStream.Write(TextToEncryptByteArray, 0, TextToEncryptByteArray.Length)
        TextCryptoStream.FlushFinalBlock()
        Return Convert.ToBase64String(TextMemoryStream.ToArray())
    End Function

No comments:

Post a Comment

Search This Blog