So many problems in such a small code sample!
For a start,
Encoding.UTF8.GetBytes
and
Encoding.Unicode.GetBytes
will return the bytes representing the characters in the specified string. But you are trying to convert a string of hexadecimal numbers to a byte array.
- Input:
ED02
- Expected output:
{ 237, 2 }
- Actual output (UTF8):
{ 69, 68, 48, 50 }
- Actual output (Unicode):
{ 69, 0, 68, 0, 48, 0, 50, 0 }
Unicode - Wikipedia[
^]
Secondly,
Convert.ToBase64String
will return a Base64 string representing the byte array you pass in. But you want to return a string containing the hexadecimal representation of the bytes you've passed in.
- Input:
{ 56, 65, 48, 70 }
- Expected output:
38413046
- Actual output:
OEEwRg==
Base64 - Wikipedia[
^]
And thirdly, according to your comment, you want to
DEcrypt the data. So why then are you creating an
ENcryptor?!
You can't just call random methods that seem to take and return the correct types. You need to understand exactly what you're trying to do, and call the correct methods to do that.
Shared Function Decrypt(ByVal text As String) As String
Dim aes As New AesCryptoServiceProvider()
aes.BlockSize = 128
aes.KeySize = 128
aes.Key = HexStringToBytes(AesKey)
aes.Mode = CipherMode.ECB
aes.Padding = PaddingMode.None
Dim src As Byte() = HexStringToBytes(text)
Using enc As ICryptoTransform = aes.CreateDecryptor()
Dim dest As Byte() = enc.TransformFinalBlock(src, 0, src.Length)
Return BytesToHexString(dest)
End Using
End Function
Shared Function HexStringToBytes(ByVal hexString As String) As Byte()
Dim result As New List(Of Byte)()
For i As Integer = 0 To hexString.Length - 1 Step 2
result.Add(Convert.ToByte(hexString.Substring(i, 2), 16))
Next
Return result.ToArray()
End Function
Shared Function BytesToHexString(ByVal bytes As Byte()) As String
Dim sb As New StringBuilder()
For i As Integer = 0 To bytes.Length - 1
sb.Append(bytes(i).ToString("X2"))
Next
Return sb.ToString()
End Function