'Convert ByteArray to Base64 in Kotlin

I am trying to convert a ByteArray to Base64 in a Spring project, written in Kotlin. I have checked existing posts but they didnt help me. Actually I am trying to convert a blob to base, but I converted the blob to byteArray so far and am struggling now to convert the bytearray to base64. This is what I am currently trying:

var inByteArray = Base64.encodeBase64(blobAsBytes)         //inByteArray : ByteArray!
var inByteArrayFormatted = Base64Utils.decode(inByteArray) //inByteArrayFormatted : ByteArray

I tried the things from this post How do I convert a byte array to Base64 in Java?, but they are just encoding strings but not directly to Base64. How can I convert a byte array to Base64? Not encoded strings but Base64?

Thanks for every help!



Solution 1:[1]

If you are using Kotlin with Java, you can use java.util.Base64 to encode a ByteArray into a String. I wrote an extension function to do this:

fun ByteArray.toBase64(): String = 
    String(Base64.getEncoder().encode(this))

// Use:
val b64 = "asdf".toByteArray().toBase64()
// YXNkZg==

Solution 2:[2]

val encodedUrl = Base64.getUrlEncoder().encodeToString(oriUrl.toByteArray())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Todd
Solution 2 madhu527