Search code examples
kotlinbase64hex

Convert Hex value to Base64 using Kotlin


I have this value:

263e5df7a93ec5f5ea6ac215ed957c30

When I fill this in on: https://8gwifi.org/base64Hex.jsp (Hex to Base64) It gives me back:

Jj5d96k+xfXqasIV7ZV8MA==

This is the expected value. However, when I try this in Kotlin,

val encodedHexB64 = Base64.encodeToString("263e5df7a93ec5f5ea6ac215ed957c30".toByteArray(UTF_8), Base64.NO_WRAP)

It gives me back:

MjYzZTVkZjdhOTNlYzVmNWVhNmFjMjE1ZWQ5NTdjMzA=

How to get the correct value in Kotlin?


Solution

  • It looks like the input string represents 16 bytes, where each byte is coded with two hex digit chars of that string.

    On the contrary toByteArray(UTF_8) encodes the string in UTF-8 encoding turning each char into one or more bytes. When you convert these bytes to base64, first you get the longer result and second — these are completely different bytes.

    I suppose the correct way to convert the input hex string into byte array would be:

        val input = "263e5df7a93ec5f5ea6ac215ed957c30"
        val bytes = input.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
    

    Then you encode these bytes to base64 as usual.

    Update: recent versions of Kotlin got API to work with hex encoded values and to convert byte arrays to Base64 and back. So the task can now be solved with the following straightforward code

    import kotlin.io.encoding.*
    
    val input = "263e5df7a93ec5f5ea6ac215ed957c30"
    val bytes = input.hexToByteArray()
    val base64 = Base64.encode(bytes)
    
    println(base64)  // Jj5d96k+xfXqasIV7ZV8MA==