Base64 and hex encoding

suggest change

Binary data (hashes, keys, images, encrypted bytes) often has to travel through channels that only handle text: JSON, URLs, HTTP headers, config files, emails, logs. Two encodings are used for that:

Neither is encryption. Anyone can decode them.

Since Kotlin 2.2 both are in the standard library and work on every platform: kotlin.io.encoding.Base64 and the toHexString() / hexToByteArray() / HexFormat functions. On the JVM you can also use java.util.Base64 and java.util.HexFormat.

This article goes deeper than the short overview in Bytes and binary data. Converting text to bytes is covered in Unicode and encodings.

Text round trip

Both encodings work on bytes, not strings. To encode text, first turn it into bytes (UTF-8 with encodeToByteArray()), and after decoding turn the bytes back with decodeToString():

import kotlin.io.encoding.Base64

fun main() {
    val text = "Zażółć 🙂"
    val bytes = text.encodeToByteArray()          // UTF-8
    println("${text.length} chars, ${bytes.size} bytes")

    val b64 = Base64.encode(bytes)
    val hex = bytes.toHexString()
    println(b64)
    println(hex)

    println(Base64.decode(b64).decodeToString())
    println(hex.hexToByteArray().decodeToString())
}

Output:

9 chars, 15 bytes
WmHFvMOzxYLEhyDwn5mC
5a61c5bcc3b3c582c48720f09f9982
Zażółć 🙂
Zażółć 🙂

The 15 bytes became 20 Base64 characters and 30 hex characters.

How Base64 works

Base64 takes 3 bytes (24 bits) at a time and splits them into four 6-bit groups. Each group (0 to 63) indexes into the alphabet A-Z a-z 0-9 + /. When the input length isn't a multiple of 3, the last group is padded with = so the output length is always a multiple of 4.

A minimal encoder shows the whole algorithm:

const val ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

fun base64(data: ByteArray): String = buildString {
    for (i in data.indices step 3) {
        val b0 = data[i].toInt() and 0xFF
        val b1 = if (i + 1 < data.size) data[i + 1].toInt() and 0xFF else 0
        val b2 = if (i + 2 < data.size) data[i + 2].toInt() and 0xFF else 0
        val n = (b0 shl 16) or (b1 shl 8) or b2   // 24 bits
        append(ALPHABET[(n shr 18) and 63])
        append(ALPHABET[(n shr 12) and 63])
        append(if (i + 1 < data.size) ALPHABET[(n shr 6) and 63] else '=')
        append(if (i + 2 < data.size) ALPHABET[n and 63] else '=')
    }
}

fun main() {
    for (s in listOf("Man", "Ma", "M", "")) {
        val bytes = s.encodeToByteArray()
        println("'$s' -> '${base64(bytes)}' (stdlib: '${kotlin.io.encoding.Base64.encode(bytes)}')")
    }
}

Output:

'Man' -> 'TWFu' (stdlib: 'TWFu')
'Ma' -> 'TWE=' (stdlib: 'TWE=')
'M' -> 'TQ==' (stdlib: 'TQ==')
'' -> '' (stdlib: '')

and 0xFF is needed because Kotlin's Byte is signed (see Bit manipulation). Use the standard library in real code. It's faster and validates input when decoding.

Encoded sizes compared (computed with toHexString() and Base64.encode()):

    1 bytes -> hex     2, base64     4
    2 bytes -> hex     4, base64     4
    3 bytes -> hex     6, base64     4
   10 bytes -> hex    20, base64    16
  100 bytes -> hex   200, base64   136
 1000 bytes -> hex  2000, base64  1336

The Base64 length is 4 * ceil(n / 3).

Base64 variants

kotlin.io.encoding.Base64 comes with 4 preconfigured instances:

Instance Alphabet Line breaks Used in
Base64.Default (or Base64) + / none most APIs, JSON, data URIs
Base64.UrlSafe - _ none URLs, file names, JWT
Base64.Mime + / every 76 chars, \r\n email (MIME)
Base64.Pem + / every 64 chars, \r\n PEM keys and certificates
import kotlin.io.encoding.Base64

fun main() {
    val data = byteArrayOf(0xFB.toByte(), 0xEF.toByte(), 0xFF.toByte(), 0x3E, 0x3F)
    println("Default: " + Base64.Default.encode(data))
    println("UrlSafe: " + Base64.UrlSafe.encode(data))
    println("Mime:    " + Base64.Mime.encode(data))
    println("Pem:     " + Base64.Pem.encode(data))

    val long = ByteArray(60) { it.toByte() }
    println(Base64.Mime.encode(long))
    println("---")
    println(Base64.Pem.encode(long))
}

Output:

Default: ++//Pj8=
UrlSafe: --__Pj8=
Mime:    ++//Pj8=
Pem:     ++//Pj8=
AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4
OTo7
---
AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v
MDEyMzQ1Njc4OTo7

The variants differ only in the last two characters of the alphabet and in line wrapping. Short inputs look the same in Default, Mime and Pem.

Padding

The = padding carries no information, so many formats (JWT, URL tokens) drop it. withPadding() returns a copy of a codec with a different PaddingOption:

Option Encode Decode
PRESENT (default) adds = requires =
ABSENT no = rejects =
PRESENT_OPTIONAL adds = accepts both
ABSENT_OPTIONAL no = accepts both
import kotlin.io.encoding.Base64

fun tryDecode(codec: Base64, s: String): String = try {
    codec.decode(s).decodeToString()
} catch (e: IllegalArgumentException) {
    "error: ${e.message}"
}

fun main() {
    val hi = "hi".encodeToByteArray()
    for (option in Base64.PaddingOption.entries) {
        val codec = Base64.UrlSafe.withPadding(option)
        println("$option")
        println("  encode:        ${codec.encode(hi)}")
        println("  decode 'aGk=': ${tryDecode(codec, "aGk=")}")
        println("  decode 'aGk':  ${tryDecode(codec, "aGk")}")
    }
}

Output:

PRESENT
  encode:        aGk=
  decode 'aGk=': hi
  decode 'aGk':  error: The padding option is set to PRESENT, but the input is not properly padded
ABSENT
  encode:        aGk
  decode 'aGk=': error: The padding option is set to ABSENT, but the input has a pad character at index 3
  decode 'aGk':  hi
PRESENT_OPTIONAL
  encode:        aGk=
  decode 'aGk=': hi
  decode 'aGk':  hi
ABSENT_OPTIONAL
  encode:        aGk
  decode 'aGk=': hi
  decode 'aGk':  hi

When you parse input produced by other systems, ABSENT_OPTIONAL or PRESENT_OPTIONAL is the forgiving choice. The codecs are immutable, so create them once and store them in a top-level val.

Decoding and errors

decode() is strict. Invalid input throws IllegalArgumentException, which you should catch whenever the data comes from outside your program:

import kotlin.io.encoding.Base64

fun tryDecode(codec: Base64, s: String): String = try {
    codec.decode(s).decodeToString()
} catch (e: IllegalArgumentException) {
    "error: ${e.message}"
}

fun main() {
    println(tryDecode(Base64, "aGVsbG8="))
    println(tryDecode(Base64, "aGVs\nbG8="))           // line break
    println(tryDecode(Base64, "aGVsbG8"))              // missing padding
    println(tryDecode(Base64, "aGk=="))                // too much padding
    println(tryDecode(Base64, "aGl="))                 // non-zero pad bits
    println(tryDecode(Base64, "-_8="))                 // URL-safe input
    println(tryDecode(Base64.Mime, "aGVs\r\nbG8= !!")) // Mime skips junk

    // decode only part of a string, without substring()
    val header = "Authorization: Basic YWxpY2U6c2VjcmV0"
    println(Base64.decode(header, startIndex = 21).decodeToString())
}

Output:

hello
error: Invalid symbol '
'(12) at index 4
error: The padding option is set to PRESENT, but the input is not properly padded
error: Symbol '='(75) at index 3 is prohibited after the pad character
error: The pad bits must be zeros
error: Invalid symbol '-'(55) at index 0
hello
alice:secret

(The number in parentheses in the error message is the character code in octal.)

Things to note:

Encoding into buffers

Besides encode() returning a String, there are variants that avoid extra allocations:

import kotlin.io.encoding.Base64

fun main() {
    val data = "Hello, world".encodeToByteArray()

    // encode a slice of the array
    println(Base64.encode(data, startIndex = 7, endIndex = 12))

    // encode to ASCII bytes instead of a String
    val ascii: ByteArray = Base64.encodeToByteArray(data)
    println(ascii.size)

    // append to an existing StringBuilder (or any Appendable)
    val sb = StringBuilder("Authorization: Basic ")
    Base64.encodeToAppendable("alice:secret".encodeToByteArray(), sb)
    println(sb)

    // write into a pre-allocated buffer, returns the number of bytes written
    val buf = ByteArray(32)
    val written = Base64.encodeIntoByteArray(data, buf)
    println("$written: ${buf.decodeToString(0, written)}")

    // decode into a buffer
    val out = ByteArray(64)
    val n = Base64.decodeIntoByteArray("SGVsbG8sIHdvcmxk", out)
    println("$n: ${out.decodeToString(0, n)}")
}

Output:

d29ybGQ=
16
Authorization: Basic YWxpY2U6c2VjcmV0
16: SGVsbG8sIHdvcmxk
12: Hello, world

encodeIntoByteArray and decodeIntoByteArray throw IndexOutOfBoundsException if the destination is too small.

Streaming large files

Loading a 500 MB file into memory just to Base64-encode it is wasteful. On the JVM, encodingWith() wraps an OutputStream so that everything written to it is encoded on the fly, and decodingWith() wraps an InputStream so that reading from it returns decoded bytes. Both are still marked experimental, so they need an opt-in:

import java.io.File
import kotlin.io.encoding.Base64
import kotlin.io.encoding.decodingWith
import kotlin.io.encoding.encodingWith
import kotlin.io.encoding.ExperimentalEncodingApi

@OptIn(ExperimentalEncodingApi::class)
fun main() {
    val input = File("photo.bin")
    input.writeBytes(ByteArray(1_000_000) { (it * 31).toByte() })

    val encoded = File("photo.b64")
    input.inputStream().use { src ->
        encoded.outputStream().encodingWith(Base64.Mime).use { dst ->
            src.copyTo(dst)
        }
    }
    println("encoded ${input.length()} bytes into ${encoded.length()} chars")
    println(encoded.useLines { it.first() })

    val decoded = File("photo.out")
    encoded.inputStream().decodingWith(Base64.Mime).use { src ->
        decoded.outputStream().use { dst -> src.copyTo(dst) }
    }
    println("round trip ok: ${decoded.readBytes().contentEquals(input.readBytes())}")
    listOf(input, encoded, decoded).forEach { it.delete() }
}

Output:

encoded 1000000 bytes into 1368422 chars
AB8+XXybutn4FzZVdJOy0fAPLk1si6rJ6AcmRWSDosHg/x49XHuaudj3FjVUc5Kx0O8OLUxriqnI
round trip ok: true

Closing the encoding stream is required: it writes the final, padded group. use {} takes care of that (see use and Closeable). The output is 1,333,336 Base64 characters plus the \r\n line breaks.

java.util.Base64

On the JVM (and on Android since API 26) java.util.Base64 is the classic alternative. You'll see it in a lot of existing code and Java libraries:

import java.util.Base64

fun main() {
    val data = "Kotlin on JVM???".encodeToByteArray()

    println(Base64.getEncoder().encodeToString(data))
    println(Base64.getUrlEncoder().encodeToString(data))
    println(Base64.getUrlEncoder().withoutPadding().encodeToString(data))

    val mime = Base64.getMimeEncoder(16, "\n".toByteArray())
    println(mime.encodeToString(data))

    val bytes = Base64.getDecoder().decode("S290bGluIG9uIEpWTT8/Pw==")
    println(bytes.decodeToString())

    // the URL decoder accepts input with or without padding
    println(Base64.getUrlDecoder().decode("S290bGluIG9uIEpWTT8_Pw").decodeToString())
    println(Base64.getUrlDecoder().decode("aGk").decodeToString())

    try {
        Base64.getDecoder().decode("S290bGlu IG9u")
    } catch (e: IllegalArgumentException) {
        println("error: ${e.message}")
    }
    println(Base64.getMimeDecoder().decode("S290bGlu IG9u").decodeToString())
}

Output:

S290bGluIG9uIEpWTT8/Pw==
S290bGluIG9uIEpWTT8_Pw==
S290bGluIG9uIEpWTT8_Pw
S290bGluIG9uIEpW
TT8/Pw==
Kotlin on JVM???
Kotlin on JVM???
hi
error: Illegal base64 character 20
Kotlin on

How the two APIs map:

kotlin.io.encoding java.util.Base64
Base64.encode(bytes) getEncoder().encodeToString(bytes)
Base64.decode(str) getDecoder().decode(str)
Base64.UrlSafe getUrlEncoder() / getUrlDecoder()
withPadding(ABSENT) withoutPadding()
Base64.Mime getMimeEncoder() / getMimeDecoder()
custom line length: not available getMimeEncoder(lineLength, separator)
outputStream.encodingWith(codec) encoder.wrap(outputStream)
inputStream.decodingWith(codec) decoder.wrap(inputStream)

The output is identical. Prefer kotlin.io.encoding.Base64 in new code, especially in multiplatform modules. Use java.util.Base64 when you need a custom MIME line length or when targeting Kotlin versions before 2.2.

Practical Base64 examples

HTTP Basic auth headers, data URIs, peeking into a JWT, and random URL-safe tokens:

import java.security.SecureRandom
import kotlin.io.encoding.Base64

fun basicAuth(user: String, password: String): String =
    "Basic " + Base64.encode("$user:$password".encodeToByteArray())

fun parseBasicAuth(header: String): Pair<String, String>? {
    if (!header.startsWith("Basic ", ignoreCase = true)) return null
    val decoded = try {
        Base64.decode(header.substring(6).trim()).decodeToString()
    } catch (e: IllegalArgumentException) {
        return null
    }
    val colon = decoded.indexOf(':')
    if (colon < 0) return null
    return decoded.substring(0, colon) to decoded.substring(colon + 1)
}

fun dataUri(mimeType: String, data: ByteArray) =
    "data:$mimeType;base64," + Base64.encode(data)

val urlNoPad = Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT_OPTIONAL)

fun jwtPayload(token: String): String {
    val parts = token.split('.')
    require(parts.size == 3) { "not a JWT" }
    return urlNoPad.decode(parts[1]).decodeToString()
}

fun randomToken(numBytes: Int = 32): String {
    val bytes = ByteArray(numBytes)
    SecureRandom().nextBytes(bytes)
    return Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT).encode(bytes)
}

fun main() {
    val header = basicAuth("alice", "s3cr:t")
    println(header)
    println(parseBasicAuth(header))
    println(parseBasicAuth("Basic ???"))

    // 1x1 transparent GIF
    val gif = Base64.decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
    println("${gif.size} bytes: " + dataUri("image/gif", gif).take(40) + "...")

    val header64 = urlNoPad.encode("""{"alg":"HS256","typ":"JWT"}""".encodeToByteArray())
    val payload64 = urlNoPad.encode("""{"sub":"42","name":"Alice","admin":true}""".encodeToByteArray())
    val token = "$header64.$payload64.c2lnbmF0dXJl"
    println(token)
    println(jwtPayload(token))

    val t = randomToken()
    println("token length ${t.length}, url-safe: ${t.all { it.isLetterOrDigit() || it == '-' || it == '_' }}")
}

Output:

Basic YWxpY2U6czNjcjp0
(alice, s3cr:t)
null
42 bytes: data:image/gif;base64,R0lGODlhAQABAIAAAA...
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJBbGljZSIsImFkbWluIjp0cnVlfQ.c2lnbmF0dXJl
{"sub":"42","name":"Alice","admin":true}
token length 43, url-safe: true

Hex

The standard library hex functions are extensions on ByteArray and on the integer types:

import java.security.MessageDigest

fun sha256Hex(text: String): String =
    MessageDigest.getInstance("SHA-256").digest(text.encodeToByteArray()).toHexString()

fun t(label: String, f: () -> Any?) {
    try { println("$label -> ${f()}") } catch (e: Exception) { println("$label -> ${e::class.simpleName}: ${e.message}") }
}

fun main() {
    println(sha256Hex("hello"))

    // parsing is case-insensitive
    t("upper") { "CAFEBABE".hexToByteArray().toHexString() }
    t("odd") { "abc".hexToByteArray() }
    t("bad char") { "zz".hexToByteArray() }
    t("prefix") { "0xff".hexToByteArray() }
    t("int") { "7fffffff".hexToInt() }
    t("int too long") { "1ffffffff".hexToInt() }
    t("negative") { "ffffffff".hexToInt() }
    t("long") { "ffffffffffffffff".hexToLong() }
    t("ulong") { "ffffffffffffffff".hexToULong() }

    val cArray = HexFormat {
        bytes {
            bytePrefix = "0x"
            byteSeparator = ", "
            bytesPerLine = 8
        }
    }
    println(ByteArray(12) { (it * 21).toByte() }.toHexString(cArray))

    val color = HexFormat { upperCase = true; number { prefix = "#"; minLength = 6; removeLeadingZeros = true } }
    println(0x00FF8800.toHexString(color))
    println(0xABC.toHexString(color))
    println("#00ff88".hexToInt(color))
    println(42.toString(16) + " " + (-42).toString(16) + " " + "-2a".toInt(16))
    println(Integer.toHexString(-42) + " " + (-42).toHexString())
}

Output:

2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
upper -> cafebabe
odd -> NumberFormatException: Expected exactly 2 hexadecimal digits at index 2, but was "c" of length 1
bad char -> NumberFormatException: Expected a hexadecimal digit at index 0, but was z
prefix -> NumberFormatException: Expected a hexadecimal digit at index 1, but was x
int -> 2147483647
int too long -> NumberFormatException: Expected the hexadecimal digit '0' at index 0, but was '1'.
The result won't fit the type being parsed.
negative -> -1
long -> -1
ulong -> 18446744073709551615
0x00, 0x15, 0x2a, 0x3f, 0x54, 0x69, 0x7e, 0x93
0xa8, 0xbd, 0xd2, 0xe7
#FF8800
#000ABC
65416
2a -2a -42
ffffffd6 ffffffd6

java.util.HexFormat

Java 17 added java.util.HexFormat. Its name clashes with Kotlin's HexFormat (which is imported by default), so import it with an alias:

import java.util.HexFormat as JHexFormat

fun main() {
    val data = byteArrayOf(0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E)

    val hex = JHexFormat.of()
    println(hex.formatHex(data))
    println(hex.parseHex("001a2b3c4d5e").contentToString())

    val mac = JHexFormat.ofDelimiter(":").withUpperCase()
    println(mac.formatHex(data))
    println(mac.parseHex("00:1A:2B:3C:4D:5E").contentToString())

    println(hex.toHexDigits(255.toByte()))
    println(hex.toHexDigits(4096))
    println(JHexFormat.fromHexDigits("1000"))
    println(JHexFormat.isHexDigit('g'.code))
}

Output:

001a2b3c4d5e
[0, 26, 43, 60, 77, 94]
00:1A:2B:3C:4D:5E
[0, 26, 43, 60, 77, 94]
ff
00001000
4096
false

It can do roughly the same things. In Kotlin code the standard library functions read better and also work outside the JVM.

Hex without the standard library helpers

On Kotlin versions before 2.2, or when you want full control, a lookup-table encoder is short and fast. Avoid joinToString { "%02x".format(it) } in hot code: it parses a format string for every byte.

private val HEX_DIGITS = "0123456789abcdef".toCharArray()

fun ByteArray.toHex(): String {
    val out = CharArray(size * 2)
    for (i in indices) {
        val v = this[i].toInt() and 0xFF
        out[i * 2] = HEX_DIGITS[v ushr 4]
        out[i * 2 + 1] = HEX_DIGITS[v and 0x0F]
    }
    return String(out)
}

fun String.fromHex(): ByteArray {
    require(length % 2 == 0) { "hex string must have an even length" }
    return ByteArray(length / 2) { i ->
        val hi = Character.digit(this[i * 2], 16)
        val lo = Character.digit(this[i * 2 + 1], 16)
        require(hi >= 0 && lo >= 0) { "invalid hex at index ${i * 2}" }
        ((hi shl 4) or lo).toByte()
    }
}

fun main() {
    val data = byteArrayOf(-1, 0, 127, -128, 16)
    println(data.toHex())
    println("ff007f8010".fromHex().contentToString())
    println("FF007F8010".fromHex().contentToString())
    try {
        "ff0g".fromHex()
    } catch (e: IllegalArgumentException) {
        println("error: ${e.message}")
    }
}

Output:

ff007f8010
[-1, 0, 127, -128, 16]
[-1, 0, 127, -128, 16]
error: invalid hex at index 2

Common mistakes

import java.net.URLDecoder
import java.net.URLEncoder
import kotlin.io.encoding.Base64

fun main() {
    val binary = byteArrayOf(0xFF.toByte(), 0xFE.toByte(), 0x80.toByte(), 0x41)

    // wrong: binary data is not valid UTF-8 text
    val asText = binary.decodeToString()
    println("via String: ${asText.encodeToByteArray().contentToString()}")

    // right: Base64 survives the round trip
    val asB64 = Base64.encode(binary)
    println("via Base64: ${Base64.decode(asB64).contentToString()}")

    // '+' in a query string turns into a space
    val token = Base64.encode(byteArrayOf(0xFB.toByte(), 0xEF.toByte()))
    val query = "token=$token"
    val received = URLDecoder.decode(query.substringAfter('='), Charsets.UTF_8)
    println("sent '$token', received '$received'")
    println("encoded: " + URLEncoder.encode(token, Charsets.UTF_8))
    println("url-safe: " + Base64.UrlSafe.encode(byteArrayOf(0xFB.toByte(), 0xEF.toByte())))
}

Output:

via String: [-17, -65, -67, -17, -65, -67, -17, -65, -67, 65]
via Base64: [-1, -2, -128, 65]
sent '++8=', received '  8='
encoded: %2B%2B8%3D
url-safe: --8=

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents