VB NET AES encrypt - vb.net

Can't reproduce an AES online encoder example using VB.Net
Trying in https://www.devglan.com/online-tools/aes-encryption-decryption with following parameters:
Text to be Encrypted: test
Cipher Mode: ECB
Key Size: 128
Secret Key: 1234567890123456
I get this output: 3fvaLg5IDlveswuXzhVQcw==
If I try in VB.Net using this function (found in https://gist.github.com/ShaneGowland/5973974):
Public Shared Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
Return ex.ToString
End Try
End Function
I get this output: 6mhZOr1dQ7PWqbRGzmMgjg== which is not matching with got at devglan.com
I tried with different paddings with no luck. What am I doing wrong?
PS: I am aware that the ECB method should not be used

Working with this function:
Public Shared Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
AES.Mode = CipherMode.ECB
AES.Key = Encoding.UTF8.GetBytes(pass)
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
Return ex.ToString
End Try
End Function

Related

VB.Net Encryption Function Not Decrypting Without Using Base64Encode

I am having a issue with decrypting, my goal is to be able to encrypt/decrypt with/without base64 encoding on the encrypted string. As of now I can encrypt/decrypt with base64 and encrypt without it but not decrypt without it. I get errors regarding the padding being incorrect.
Thanks in advance!
Here is my encryption/decryption function:
Public Function DoCryptWork(Type As String, Data As String) As String
Dim Pass As String = Hasher.TextBoxPassword.Text
Dim Salt As String = Hasher.TextBoxSalt.Text
Dim Vect As String = Hasher.TextBoxIntVector.Text
Select Case Type
Case "e"
Try
Dim PassPhrase As String = Pass
Dim SaltValue As String = Salt
Dim HashAlgorithm As String = My.Settings.HashAlgorithm
Dim PasswordIterations As Integer = 2
Dim InitVector As String = Vect
Dim KeySize As Integer = 256
Dim InitVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(SaltValue)
Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(Data)
Dim Password As New PasswordDeriveBytes(PassPhrase, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = Password.GetBytes(KeySize \ 8)
Dim SymmetricKey As New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitVectorBytes)
Dim MemoryStream As New MemoryStream()
Dim CryptoStream As New CryptoStream(MemoryStream, Encryptor, CryptoStreamMode.Write)
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
CryptoStream.FlushFinalBlock()
Dim CipherTextBytes As Byte() = MemoryStream.ToArray()
MemoryStream.Close()
CryptoStream.Close()
Dim CipherText As String = Nothing
If My.Settings.Base64EncodeMD5Hash = True Then
CipherText = Convert.ToBase64String(CipherTextBytes)
Return CipherText
Else
Dim TextCipher As New StringBuilder()
For n As Integer = 0 To CipherTextBytes.Length - 1
TextCipher.Append(CipherTextBytes(n).ToString("X2"))
Next n
CipherText = TextCipher.ToString()
Return CipherText
End If
Catch ex As Exception
MsgBox("Encryption was unsuccessfull!", MsgBoxStyle.Critical, "Error")
Return "Encryption was unsuccessfull!"
End Try
Case "d"
Try
Dim PassPhrase As String = Pass
Dim SaltValue As String = Salt
Dim HashAlgorithm As String = My.Settings.HashAlgorithm
Dim PasswordIterations As Integer = 2
Dim InitVector As String = Vect
Dim KeySize As Integer = 256
Dim InitVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(SaltValue)
Dim CipherTextBytes As Byte() = Nothing
If My.Settings.Base64EncodeMD5Hash = True Then
CipherTextBytes = Convert.FromBase64String(Data)
Else
Dim bytedata As Byte() = Encoding.UTF8.GetBytes(Data)
CipherTextBytes = bytedata
End If
Dim Password As New PasswordDeriveBytes(PassPhrase, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = Password.GetBytes(KeySize \ 8)
Dim SymmetricKey As New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitVectorBytes)
Dim MemoryStream As New MemoryStream(CipherTextBytes)
Dim CryptoStream As New CryptoStream(MemoryStream, Decryptor, CryptoStreamMode.Read)
Dim PlainTextBytes As Byte() = New Byte(CipherTextBytes.Length - 1) {}
Dim DecryptedByteCount As Integer = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length)
MemoryStream.Close()
CryptoStream.Close()
Dim PlainText As String = Encoding.UTF8.GetString(PlainTextBytes, 0, DecryptedByteCount)
Return PlainText
Catch Ex As Exception
MsgBox("Decryption was unsuccessfull!" & vbNewLine & vbNewLine & Ex.ToString(), MsgBoxStyle.Critical, "Error")
Return "Decryption was unsuccessfull!"
End Try
Case Else
Return "Error! Invalid Case Selected We should never see this but just to be safe we'll show this message if the wrong case is selected!"
End Select
Return True
End Function
I call the function as so:
TextBoxOutput.Text = Encryption.DoCryptWork("e", TextBoxInput.Text) ' encrypt data.
TextBoxOutput.Text = Encryption.DoCryptWork("d", TextBoxInput.Text) ' decrypt data.
When you convert the bytes to hex, you output two hex digits per byte. When you convert that hex back to bytes, you're converting every hex digit to a byte instead of every pair of hex digits.
Actually, I just took another look and noticed that you're not even keeping the earlier bytes. This loop:
For n As Integer = 0 To Data.Length - 1
CipherTextBytes = Convert.ToByte(Data(n))
Next n
sets CipherTextBytes on each iteration so you're going to replace the previous byte each time, so you only end up keeping the byte from the last digit.

vb.net "Padding is invalid and cannot be removed" switching bewteen 256 and 128 bit keys

I have an issue when trying to switch between 256 and 128 bit encryption with my code. If I keep it at 256bit, it works fine, but when I try it again using a 128 bit key, I get an error of "Padding is invalid and cannot be removed." Any help is much appreciated. I am no pro at encryption. The error is thrown when the "DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)" part of the AES_Decrypt function is called.
Public Shared Function GenerateEncryptionKey(Optional ByVal keySizeIndex As Integer = 1) As Byte()
'Generate a Key.
Dim rm As RijndaelManaged = New RijndaelManaged()
Select Case keySizeIndex
Case 0
rm.KeySize = 128
Case 1
rm.KeySize = 256
Case Else
rm.KeySize = 256
End Select
rm.GenerateKey()
Return rm.Key
End Function
Public Shared Function AES_Encrypt(ByVal input As String, ByVal pass As Byte()) As String
Dim AES As New RijndaelManaged
Dim encrypted As String = ""
Dim hash As Byte()
Dim byteLength As Integer
Try
byteLength = pass.Length
ReDim hash(byteLength - 1)
Array.Copy(pass, 0, hash, 0, 16)
If (byteLength > 16) Then
Array.Copy(pass, 0, hash, 15, 16)
End If
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.Encoding.Unicode.GetBytes(input)
'Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
Dim testBuffer As Byte() = DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
encrypted = ""
End Try
Return encrypted
End Function
Public Shared Function AES_Decrypt(ByVal input As String, ByVal pass As Byte()) As String
Dim AES As New RijndaelManaged
Dim decrypted As String = ""
Dim hash As Byte()
Dim byteLength As Integer
Try
byteLength = pass.Length
ReDim hash(byteLength - 1)
Array.Copy(pass, 0, hash, 0, 16)
If (byteLength > 16) Then
Array.Copy(pass, 0, hash, 15, 16)
End If
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(input)
Dim testBuffer As Byte() = DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)
decrypted = System.Text.Encoding.Unicode.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
'decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
decrypted = ""
End Try
Return decrypted
End Function

Sage Pay error 3045 : The Currency field is missing. MALFORMED

I am trying to upgrade sage pay version from 2.22 to 3.00 and I am using Form Intergration to submit the values to Sage. The codes written asp.net(VB). In 2.2, it was using "SimpleXor encryption algorithm", but that doesn't allowed in version 3.00 and as a result, I am getting the below error message:
This transaction attempt has failed. We are unable to redirect you back to the web store from which you were purchasing. The details of the failure are given below.
Status: INVALID
Status Detail: 5068 : The encryption method is not supported by this protocol version.
I found, version 3.00 allowed only AES encryption, And I have added the below code in class file for encryption:
Public Shared Function AESEncrypt(ByVal clearText As String) As String
Dim EncryptionKey As String = "MAKV2SPBNI99212"
Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText)
Using encryptor As Aes = Aes.Create()
Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
&H65, &H64, &H76, &H65, &H64, &H65, _
&H76})
encryptor.Key = pdb.GetBytes(32)
encryptor.IV = pdb.GetBytes(16)
Using ms As New MemoryStream()
Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
cs.Write(clearBytes, 0, clearBytes.Length)
cs.Close()
End Using
clearText = Convert.ToBase64String(ms.ToArray())
End Using
End Using
Return clearText
End Function
And in main .vb file, I change below code:
Dim strXOR As String = simpleXor(strPost, strEncryptionPassword)
strCrypt = base64Encode(strXOR)
To
Dim aesEncrypt As String = AESEncrypt(strPost)
strCrypt = "#" & aesEncrypt
Sorry, I am begginer on this. Is there any mistakes I did in my class file Or in main vb file? Do I need to base64encode after aes encryption?
Thank you in advance.
OK. Compete answer rewrite.
Ditch the code you have - I found it on another site and it isn't going to work.
Instead, use the stuff below (which I've adapted very slightly from here) :
Public Shared Function AESEncryption(ByVal strCrypt As String, ByVal strEncryptionPassword As String) As String
Dim keyAndIvBytes As Byte() = UTF8Encoding.UTF8.GetBytes(strEncryptionPassword)
Using AES As New RijndaelManaged()
' Set the mode, padding and block size for the key
AES.Padding = PaddingMode.PKCS7
AES.Mode = CipherMode.CBC
AES.KeySize = 128
AES.BlockSize = 128
' Encrypt the string to an array of bytes.
Dim encrypted As Byte() = EncryptStringToBytes(strCrypt, keyAndIvBytes, keyAndIvBytes)
AESEncryption = "#" & BitConverter.ToString(encrypted).Replace("-", "").ToUpper
' System.Console.WriteLine(AESEncryption)
End Using
End Function
Public Shared Function AESDecryption(ByVal strCrypt As String, ByVal strEncryptionPassword As String) As String
Dim keyAndIvBytes As [Byte]() = UTF8Encoding.UTF8.GetBytes(strEncryptionPassword)
' Create a new instance of the RijndaelManaged
' class. This generates a new key and initialization
' vector (IV).
Using AES As New RijndaelManaged()
' Set the mode, padding and block size for the key
AES.Padding = PaddingMode.PKCS7
AES.Mode = CipherMode.CBC
AES.KeySize = 128
AES.BlockSize = 128
Dim encryptedData As Byte() = StringToByteArray(strCrypt.Remove(0, 1))
Dim roundtrip As String = DecryptStringFromBytes(encryptedData, keyAndIvBytes, keyAndIvBytes)
AESDecryption = roundtrip
End Using
End Function
Shared Function byteArrayToHexString(ByVal ba As Byte()) As String
Return BitConverter.ToString(ba).Replace("-", "")
End Function
Shared Function StringToByteArray(ByVal hex As String) As Byte()
Return Enumerable.Range(0, hex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(hex.Substring(x, 2), 16)).ToArray()
End Function
Shared Function EncryptStringToBytes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
' Check arguments.
If plainText Is Nothing OrElse plainText.Length <= 0 Then
Throw New ArgumentNullException("plainText")
End If
If Key Is Nothing OrElse Key.Length <= 0 Then
Throw New ArgumentNullException("Key")
End If
If IV Is Nothing OrElse IV.Length <= 0 Then
Throw New ArgumentNullException("IV")
End If
Dim encrypted() As Byte
' Create an RijndaelManaged object
' with the specified key and IV.
Using AES As New RijndaelManaged()
AES.Padding = PaddingMode.PKCS7
AES.Mode = CipherMode.CBC
AES.KeySize = 128
AES.BlockSize = 128
AES.Key = Key
AES.IV = IV
' Create a decrytor to perform the stream transform.
Dim encryptor As ICryptoTransform = AES.CreateEncryptor(AES.Key, AES.IV)
' Create the streams used for encryption.
Using msEncrypt As New MemoryStream()
Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
Using swEncrypt As New StreamWriter(csEncrypt)
'Write all data to the stream.
swEncrypt.Write(plainText)
End Using
encrypted = msEncrypt.ToArray()
End Using
End Using
End Using
' Return the encrypted bytes from the memory stream.
Return encrypted
End Function 'EncryptStringToBytes
Shared Function DecryptStringFromBytes(ByVal cipherText() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
' Check arguments.
If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
Throw New ArgumentNullException("cipherText")
End If
If Key Is Nothing OrElse Key.Length <= 0 Then
Throw New ArgumentNullException("Key")
End If
If IV Is Nothing OrElse IV.Length <= 0 Then
Throw New ArgumentNullException("IV")
End If
' Declare the string used to hold
' the decrypted text.
Dim plaintext As String = Nothing
' Create an RijndaelManaged object
' with the specified key and IV.
Using AES As New RijndaelManaged
AES.Padding = PaddingMode.PKCS7
AES.Mode = CipherMode.CBC
AES.KeySize = 128
AES.BlockSize = 128
'AES.Key = Key
'AES.IV = IV
' Create a decrytor to perform the stream transform.
Dim decryptor As ICryptoTransform = AES.CreateDecryptor(Key, IV)
' Create the streams used for decryption.
Using msDecrypt As New MemoryStream(cipherText)
Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
Using srDecrypt As New StreamReader(csDecrypt)
' Read the decrypted bytes from the decrypting stream
' and place them in a string.
plaintext = srDecrypt.ReadToEnd()
End Using
End Using
End Using
End Using
Return plaintext
End Function
And in your main.vb file change:
Dim strXOR As String = simpleXor(strPost, strEncryptionPassword)
strCrypt = base64Encode(strXOR)
To:
strCrypt=AESEncryption(strPost, strEncryptionPassword)

Shorten a string containing data

I am creating an application to create a key that is unique to each computer. This info is derived from the OS serial number and processorID.
Is there a way to 'shorten' a string? Maybe by converting it to HEX or something else...
The reason is this: I used to use a VB6 section of code (http://www.planet-source-code.com/vb...48926&lngWId=1) that gets the details and the output is only 13 digits long. Mine is a lot longer, but gets the same info...
BTW, the link I posted above won multiple awards, but I am having huge trouble in converting it to .NET. Has anyone by any chance converted it, or know of someone who has? Or a tool that actually works?
Thanks
EDIT
Here is the full working link: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48926&lngWId=1
It sounds like you want a 'hashing algorithm' or 'hash function'. They are a common concept: http://en.wikipedia.org/wiki/Hash_function
Generally speaking you can simply write your own function to take a string and return a hashed number but there is some suitable code here that uses the .NET framework: http://support.microsoft.com/kb/301053
Here is a working example which retrieves the Processor ID, for the first Processor found, and the OS Serial Number; it concatenates these to strings together and then performs various encodings on them.
This is a simple VB.Net Console project. Be sure to reference the System.Management assembly in your project. Just copy and paste this code example into the main module, set a breakpoint at the end of Sub Main(), and look at the various results.
Module Module1
Sub Main()
Dim uniqueID As String = GetUniqueID()
' convert it to a base64 string
Dim encoding As New Text.ASCIIEncoding()
Dim result1 = Convert.ToBase64String(encoding.GetBytes(uniqueID))
' compress it
Dim result2 As String = CompressString(uniqueID)
Dim result3 As String = DecompressString(result2)
' encrypt it
Dim result4 As String = AES_Encrypt(uniqueID, "password")
Dim result5 As String = AES_Decrypt(result4, "password")
' hash it
Dim result6 As String = HashString(uniqueID)
End Sub
Private Function GetUniqueID() As String
Dim result As String = GetOSSerialNumber()
Dim processorIDs() As String = GetProcessorIDs()
If ((processorIDs IsNot Nothing) AndAlso (processorIDs.Count > 0)) Then
result &= processorIDs(0)
End If
Return result
End Function
Private Function GetProcessorIDs() As String()
Dim result As New List(Of String)
Dim searcher = New System.Management.ManagementObjectSearcher("Select ProcessorId from Win32_Processor")
For Each managementObj In searcher.Get()
result.Add(CStr(managementObj.Properties("ProcessorId").Value))
Next
Return result.ToArray()
End Function
Private Function GetOSSerialNumber() As String
Dim result As String = ""
Dim searcher = New System.Management.ManagementObjectSearcher("Select SerialNumber from Win32_OperatingSystem")
For Each managementObj In searcher.Get()
result = CStr(managementObj.Properties("SerialNumber").Value)
Next
Return result
End Function
Public Function CompressString(ByVal source As String) As String
Dim result As String = ""
Dim encoding As New Text.ASCIIEncoding()
Dim bytes() As Byte = encoding.GetBytes(source)
Using ms As New IO.MemoryStream
Using gzsw As New System.IO.Compression.GZipStream(ms, IO.Compression.CompressionMode.Compress)
gzsw.Write(bytes, 0, bytes.Length)
gzsw.Close()
result = Convert.ToBase64String(ms.ToArray)
End Using
End Using
Return result
End Function
Public Function DecompressString(ByVal source As String) As String
Dim result As String = ""
Dim bytes() As Byte = Convert.FromBase64String(source)
Using ms As New IO.MemoryStream(bytes)
Using gzsw As New System.IO.Compression.GZipStream(ms, IO.Compression.CompressionMode.Decompress)
Dim data(CInt(ms.Length)) As Byte
gzsw.Read(data, 0, CInt(ms.Length))
Dim encoding As New Text.ASCIIEncoding()
result = encoding.GetString(data)
End Using
End Using
Return result
End Function
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
End Try
Return encrypted
End Function
Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim decrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(input)
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
End Try
Return decrypted
End Function
Private Function HashString(ByVal source As String) As String
Dim encoding As New Text.ASCIIEncoding()
Dim bytes() As Byte = encoding.GetBytes(source)
Dim workingHash() As Byte = New System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(bytes)
Dim result As String = ""
For Each b In workingHash
result = result & b.ToString("X2")
Next
Return result
End Function
End Module

AES encryption/decryption

Here is some code that works well for strings:
Public Function AESEncrypt(ByVal PlainText As String, ByVal Password As String, ByVal salt As String)
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
Dim PasswordIterations As String = 2
Dim InitialVector As String = "CanEncryption123" 'This should be a string of 16 ASCII characters.
Dim KeySize As Integer = 256 'Can be 128, 192, or 256.
If (String.IsNullOrEmpty(PlainText)) Then
Return ""
Exit Function
End If
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(PlainText)
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim CipherTextBytes As Byte() = Nothing
Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)
Using MemStream As New MemoryStream()
Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
CryptoStream.FlushFinalBlock()
CipherTextBytes = MemStream.ToArray()
MemStream.Close()
CryptoStream.Close()
End Using
End Using
End Using
SymmetricKey.Clear()
Return Convert.ToBase64String(CipherTextBytes)
End Function
Public Function AESDecrypt(ByVal CipherText As String, ByVal password As String, ByVal salt As String) As String
Dim HashAlgorithm As String = "SHA1"
Dim PasswordIterations As String = 2
Dim InitialVector As String = "CanEncryption123"
Dim KeySize As Integer = 256
If (String.IsNullOrEmpty(CipherText)) Then
Return ""
End If
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim CipherTextBytes As Byte() = Convert.FromBase64String(CipherText)
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(password, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim PlainTextBytes As Byte() = New Byte(CipherTextBytes.Length - 1) {}
Dim ByteCount As Integer = 0
Using Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)
Using MemStream As MemoryStream = New MemoryStream(CipherTextBytes)
Using CryptoStream As CryptoStream = New CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)
ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length)
MemStream.Close()
CryptoStream.Close()
End Using
End Using
End Using
SymmetricKey.Clear()
Return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount)
End Function
Can I have some help in modifying these functions to encrypt/decrypt byte arrays rather than strings. Also, to have the functions return the encrypted/decrypted byte array, rather than a string.
thanks
I am using this (found on Google) for strings AES Encryption/Decryption:
Imports System.Security.Cryptography
Namespace TextCrypters
Public Class AESCrypter
Public Shared pass As String = "password"
Public Shared Function AES_Encrypt(ByVal input As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
Return Nothing
End Try
End Function
Public Shared Function AES_Decrypt(ByVal input As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim decrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(input)
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return decrypted
Catch ex As Exception
Return Nothing
End Try
End Function
End Class
End Namespace
To use it just do this:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox2.Text = AESCrypter.AES_Encrypt(TextBox1.Text)
End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox4.Text = AESCrypter.AES_Decrypt(TextBox3.Text)
End Sub
Just copy everything in a new function starting from Dim ByteCount As Integer = 0 to SymmetricKey.Clear() to get rid of all strings? After that you only need to define the arguments to the function.
The simplest way is to use a wrapper function that just converts the byte array to a string, encrypts it with your AESEncrypt function, and converts the string back to a byte array. You can find conversion functions for VB.net here.
Edited to add: I think I got this wrong. It seems that a VB String is in Unicode format, and these translation functions convert it to/from a UTF8 byte array. Which is not what was required...
Public Function AESEncrypt(ByVal PlainBytes As Byte, ByVal Password As String, ByVal salt As String)
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
Dim PasswordIterations As String = 2
Dim InitialVector As String = "CanEncryption123" 'This should be a string of 16 ASCII characters.
Dim KeySize As Integer = 256 'Can be 128, 192, or 256.
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim CipherTextBytes As Byte() = Nothing
Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)
Using MemStream As New MemoryStream()
Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
CryptoStream.Write(PlainBytes, 0, PlainBytes.Length)
CryptoStream.FlushFinalBlock()
CipherTextBytes = MemStream.ToArray()
MemStream.Close()
CryptoStream.Close()
End Using
End Using
End Using
SymmetricKey.Clear()
Return Convert.ToBase64String(CipherTextBytes)
End Function
Public Function AESDecrypt(ByVal CipherBytes As Byte, ByVal password As String, ByVal salt As String) As String
Dim HashAlgorithm As String = "SHA1"
Dim PasswordIterations As String = 2
Dim InitialVector As String = "CanEncryption123"
Dim KeySize As Integer = 256
If (String.IsNullOrEmpty(CipherText)) Then
Return ""
End If
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(password, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim PlainTextBytes As Byte() = New Byte(CipherBytes.Length - 1) {}
Dim ByteCount As Integer = 0
Using Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)
Using MemStream As MemoryStream = New MemoryStream(CipherBytes)
Using CryptoStream As CryptoStream = New CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)
ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length)
MemStream.Close()
CryptoStream.Close()
End Using
End Using
End Using
SymmetricKey.Clear()
Return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount)
End Function
The code you are using actually converts the input string to byte array. This code accepts byte array.