Base64 Encoding in Kotlin

Here’s the translation of the Base64 Encoding example from Go to Kotlin, formatted in Markdown suitable for Hugo:

Kotlin provides built-in support for base64 encoding/decoding.

import java.util.Base64

fun main() {
    // Here's the string we'll encode/decode.
    val data = "abc123!?$*&()'-=@~"

    // Kotlin supports both standard and URL-compatible
    // base64. Here's how to encode using the standard
    // encoder.
    val sEnc = Base64.getEncoder().encodeToString(data.toByteArray())
    println(sEnc)

    // Decoding may return an error, which you can check
    // if you don't already know the input to be
    // well-formed.
    val sDec = String(Base64.getDecoder().decode(sEnc))
    println(sDec)
    println()

    // This encodes/decodes using a URL-compatible base64
    // format.
    val uEnc = Base64.getUrlEncoder().encodeToString(data.toByteArray())
    println(uEnc)
    val uDec = String(Base64.getUrlDecoder().decode(uEnc))
    println(uDec)
}

The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.

$ kotlinc base64-encoding.kt -include-runtime -d base64-encoding.jar
$ java -jar base64-encoding.jar
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

In Kotlin, we use the java.util.Base64 class for base64 encoding and decoding. The getEncoder() and getDecoder() methods are used for standard base64, while getUrlEncoder() and getUrlDecoder() are used for URL-safe base64.

The encodeToString() method is used to encode a ByteArray to a base64 String, and decode() is used to decode a base64 String back to a ByteArray. We convert between String and ByteArray using toByteArray() and the String constructor that takes a ByteArray, respectively.

Note that in Kotlin, we don’t need to explicitly handle errors when decoding, as the decode() method throws an IllegalArgumentException if the input is not properly encoded.