6

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!

IonicMan
  • 743
  • 1
  • 12
  • 31
  • 1
    And what is `Base64` in your understanding? Because that answer is exactly what you need, but I think you are misunderstanding something. And in your code you are converting to base64 and then converting back, kind of a no-op. – Shadov Oct 22 '20 at 16:28
  • Yeah Base64 is a string representation of binary data, it uses 64 characters (a-z, A-Z, 0-9 and two more) – cactustictacs Oct 22 '20 at 17:49

2 Answers2

14

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==
Todd
  • 30,472
  • 11
  • 81
  • 89
0
val encodedUrl = Base64.getUrlEncoder().encodeToString(oriUrl.toByteArray())
madhu527
  • 4,644
  • 1
  • 28
  • 29