Jason Edel-Brock Jason Edel-Brock - 1 year ago 98
Vb.net Question

VB.Net String to Bytes

I am having a issue converting string to bytes and being able to decrypt it.
It encrypts just fine but decryption fails.

Here is my function:

Dim CipherText As String = Nothing

If My.Settings.Base64EncodeMD5Hash = True Then

CipherText = Convert.ToBase64String(CipherTextBytes)
Return CipherText

Else

Dim StrBuilder As New StringBuilder()

For n As Integer = 0 To CipherTextBytes.Length - 1

StrBuilder.Append(CipherTextBytes(n).ToString("X2"))

Next n

Return StrBuilder.ToString()

End If


I want it to just return the encrypted string if not base64 encoded.

Here is my decrypt code:

If My.Settings.Base64EncodeMD5Hash = True Then

CipherTextBytes = Convert.FromBase64String(Data)

Else

For n As Integer = 0 To Data.Length - 1

CipherTextBytes = Convert.ToByte(Data(n))

Next n

End If


How I call the function

TextBoxOutput.Text = Encryption.DoCryptWork("decrypt", TextBoxInput.Text)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download