Try it yourself with our free Base64 tool — runs entirely in your browser, no signup needed.

How to Base64 decode in Kotlin

How to Base64 decode in Kotlin

Base64 decoding is a crucial operation in many applications, especially when working with data encoding and transmission. In Kotlin, decoding Base64 strings can be achieved using the built-in java.util.Base64 class. In this article, we will explore how to perform Base64 decoding in Kotlin, covering the most common use case, edge cases, common mistakes, and performance tips.

Quick Example

Here is a minimal example that decodes a Base64 string in Kotlin:

import java.util.Base64

fun decodeBase64(base64String: String): String {
    return String(Base64.getDecoder().decode(base64String))
}

// Usage:
val base64String = "SGVsbG8gd29ybGQh"
val decodedString = decodeBase64(base64String)
println(decodedString) // Output: "Hello world!"

Step-by-Step Breakdown

Let's walk through the code line by line:

  • import java.util.Base64: We import the Base64 class from the Java standard library, which provides the necessary functionality for Base64 decoding.
  • fun decodeBase64(base64String: String): String { ... }: We define a function decodeBase64 that takes a Base64-encoded string as input and returns the decoded string.
  • return String(Base64.getDecoder().decode(base64String)): We use the getDecoder() method to obtain a Base64.Decoder instance, which we then use to decode the input string using the decode() method. The resulting byte array is converted to a string using the String constructor.

Handling Edge Cases

Here are some common edge cases to consider:

Empty/Null Input

fun decodeBase64(base64String: String?): String? {
    return base64String?.let { String(Base64.getDecoder().decode(it)) }
}

// Usage:
val base64String: String? = null
val decodedString = decodeBase64(base64String)
println(decodedString) // Output: null

In this example, we modify the decodeBase64 function to accept a nullable String? input. We use the let function to safely decode the input string only if it is not null.

Invalid Input

try {
    val base64String = "InvalidBase64String"
    val decodedString = decodeBase64(base64String)
    println(decodedString)
} catch (e: IllegalArgumentException) {
    println("Invalid Base64 string")
}

In this example, we attempt to decode an invalid Base64 string, which throws an IllegalArgumentException. We catch this exception and print an error message.

Large Input

fun decodeBase64LargeInput(base64String: String): String {
    val decoder = Base64.getDecoder()
    val bytes = decoder.decode(base64String)
    return String(bytes, 0, bytes.size)
}

// Usage:
val largeBase64String = "Very large Base64 string..."
val decodedString = decodeBase64LargeInput(largeBase64String)
println(decodedString)

In this example, we define a separate function decodeBase64LargeInput to handle large input strings. We use the decode() method to decode the input string in chunks, and then construct the resulting string using the String constructor.

Unicode/Special Characters

fun decodeBase64Unicode(base64String: String): String {
    val decoder = Base64.getDecoder()
    val bytes = decoder.decode(base64String)
    return String(bytes, Charsets.UTF_8)
}

// Usage:
val base64String = "SGVsbG8gd29ybGQh" // contains non-ASCII characters
val decodedString = decodeBase64Unicode(base64String)
println(decodedString) // Output: "Hello world!"

In this example, we define a separate function decodeBase64Unicode to handle input strings containing Unicode characters. We use the Charsets.UTF_8 charset to ensure that the resulting string is correctly decoded.

Common Mistakes

Here are some common mistakes to avoid:

1. Not handling null input

// Wrong code:
fun decodeBase64(base64String: String): String {
    return String(Base64.getDecoder().decode(base64String))
}

// Corrected code:
fun decodeBase64(base64String: String?): String? {
    return base64String?.let { String(Base64.getDecoder().decode(it)) }
}

2. Not handling invalid input

// Wrong code:
fun decodeBase64(base64String: String): String {
    return String(Base64.getDecoder().decode(base64String))
}

// Corrected code:
try {
    val base64String = "InvalidBase64String"
    val decodedString = decodeBase64(base64String)
    println(decodedString)
} catch (e: IllegalArgumentException) {
    println("Invalid Base64 string")
}

3. Not using the correct charset

// Wrong code:
fun decodeBase64(base64String: String): String {
    return String(Base64.getDecoder().decode(base64String))
}

// Corrected code:
fun decodeBase64(base64String: String): String {
    return String(Base64.getDecoder().decode(base64String), Charsets.UTF_8)
}

Performance Tips

Here are some performance tips to keep in mind:

  • Use the getDecoder() method to obtain a reusable Base64.Decoder instance instead of creating a new instance for each decoding operation.
  • Use the decode() method to decode the input string in chunks instead of loading the entire string into memory.

FAQ

Q: What is the difference between Base64 and Base64URL?

A: Base64URL is a variant of Base64 that uses a different character set and is more suitable for use in URLs.

Q: How do I encode a string to Base64 in Kotlin?

A: You can use the java.util.Base64 class to encode a string to Base64. See the Kotlin documentation for more information.

Q: Can I use the String constructor to decode a Base64 string?

A: No, the String constructor is not suitable for decoding Base64 strings. Use the java.util.Base64 class instead.

Q: How do I handle large input strings when decoding Base64?

A: Use the decode() method to decode the input string in chunks instead of loading the entire string into memory.

Q: What is the best way to handle invalid input when decoding Base64?

A: Catch the IllegalArgumentException exception thrown by the decode() method and handle it accordingly.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp