Hex value to Base64 is not in correct format VB.net

Viewed 369

I am trying to convert string to hex then to Base64, it is working but but base64value getting is not matching - Vs 2008(.net 3.5) & vs 2019 (.net 4.6)

this my code --HEX string

Dim QrCodeHex as string ="010c426f6273205265636f726473020f3331303132323339333530303030330314323032322d30342d32355431353a33303a30305a0407313030302e303005063135302e3030"
dim QrCodeBase64En as string = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(QrCodeHex))

I am getting this result- is wrong

MDEwYzQyNmY2MjczMjA1MjY1NjM2ZjcyNjQ3MzAyMGYzMzMxMzAzMTMyMzIzMzM5MzMzNTMwMzAzMDMwMzMwMzE0MzIzMDMyMzIyZDMwMzQyZDMyMzU1NDMxMzUzYTMzMzAzYTMwMzA1YTA0MDczMTMwMzAzMDJlMzAzMDA1MDYzMTM1MzAyZTMwMzA=

Correct Result is

AQxCb2JzIFJlY29yZHMCDzMxMDEyMjM5MzUwMDAwMwMUMjAyMi0wNC0yNVQxNTozMDowMFoEBzEwMDAuMDAFBjE1MC4wMA==

how do i get it.

1 Answers

System.Text.Encoding.UTF8.GetBytes converts a (regular) string to a byte array. However, in your case, you don't have a regular string ("Bobs Records...") but a hexadecimal representation of the byte array ("010c426f62..."). So you need to convert that hex representation to a byte array first:

Dim QrCodeHex As String = "010c426f6273205265636f726473020f3331303132323339333530303030330314323032322d30342d32355431353a33303a30305a0407313030302e303005063135302e3030"
    
' Hex to bytes
Dim bytes As Byte() = BigInteger.
    Parse(QrCodeHex, NumberStyles.AllowHexSpecifier).
    ToByteArray().Reverse().ToArray()
    
Dim QrCodeBase64En As String = Convert.ToBase64String(bytes)
    
Console.WriteLine(QrCodeBase64En)

(fiddle)

Note: I just used BigInteger for conversion, since it was the most compact way to do so without relying on .NET 5+ features. (The Reverse is required because, by default, it outputs the number as little-endian.) See this question for alternatives: How can I convert a hex string to a byte array?

Related