Imports System.Security.Cryptography
Imports Microsoft.VisualBasic
Imports System.Security.Principal
Dim md5Hasher As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim hashedBytes As Byte()
hashedBytes = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes("password"))
Console.WriteLine("Hashed Pass : " & Convert.ToBase64String(hashedBytes))
Console.WriteLine("Encrypted Answer : " & EncryptText("answer", "12345"))
Public Function EncryptText(ByVal text As String, ByVal encryptKey As String) As String
text = StripNullCharacters(text)
Dim bytValue() As Byte = Encoding.UTF8.GetBytes(text.ToCharArray())
Dim intLength As Integer = Len(encryptKey)
encryptKey = Strings.Left(encryptKey, 32)
encryptKey = encryptKey & Strings.StrDup(32 - intLength, "X")
Dim bytEncryptKey() As Byte = Encoding.UTF8.GetBytes(encryptKey.ToCharArray)
Dim memStream As New MemoryStream()
Dim cryptoStream As CryptoStream = Nothing
Dim rijndaelEncryptor As RijndaelManaged = New RijndaelManaged()
Dim encryptedBytes() As Byte
cryptoStream = New CryptoStream(memStream, rijndaelEncryptor.CreateEncryptor(bytEncryptKey, ByteIV), CryptoStreamMode.Write)
cryptoStream.Write(bytValue, 0, bytValue.Length)
cryptoStream.FlushFinalBlock()
encryptedBytes = memStream.ToArray
If memStream IsNot Nothing Then
If cryptoStream IsNot Nothing Then
Return Convert.ToBase64String(encryptedBytes)
Public Function DecryptText(ByVal text As String, ByVal decryptKey As String) As String
Dim bytEncryptedValue() As Byte = Convert.FromBase64String(text)
Dim intLength As Integer = Len(decryptKey)
decryptKey = Strings.Left(decryptKey, 32)
decryptKey = decryptKey & Strings.StrDup(32 - intLength, "X")
Dim bytDecryptKey() As Byte = Encoding.UTF8.GetBytes(decryptKey.ToCharArray)
Dim memStream As MemoryStream = New MemoryStream(bytEncryptedValue)
Dim cryptoStream As CryptoStream = Nothing
Dim rijndaelDecryptor As RijndaelManaged = New RijndaelManaged()
Dim decryptedBytes(bytEncryptedValue.Length) As Byte
cryptoStream = New CryptoStream(memStream, rijndaelDecryptor.CreateDecryptor(bytDecryptKey, ByteIV), CryptoStreamMode.Read)
cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length)
If memStream IsNot Nothing Then
If cryptoStream IsNot Nothing Then
Return StripNullCharacters(Encoding.UTF8.GetString(decryptedBytes))
Public Function StripNullCharacters(ByVal stringWithNulls As String) As String
Dim intPosition As Integer
Dim strOutput As String = stringWithNulls
intPosition = InStr(intPosition, stringWithNulls, vbNullChar)
strOutput = Left$(strOutput, intPosition - 1) & Right$(strOutput, Len(strOutput) - intPosition)
If intPosition > strOutput.Length Then
Private _byteIV() As Byte
Private ReadOnly Property ByteIV() As Byte()
If _byteIV Is Nothing Then
_byteIV = New Byte() {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62}