This post will discuss Base64 encoding and decoding in Kotlin.

1. Using Base64 class

The idea is to use the encodeToString() function from Base64.Encoder for encoding the specified byte array into the base64 encoded string. To decode the base64 encoded string back to the byte array, use the decode() function from the Base64.Decoder class.

Download Code

Output:

Encoded Data: U29tZSB0ZXh0
Decoded Data: Some text

 
You can’t use a basic encoding to encode an URL. You should use the “URL and Filename safe” type Base64 encoding and decoding scheme. The following code example demonstrates this:

Download Code

Output:

Encoded URL: aHR0cHM6Ly93d3cudGVjaGllZGVsaWdodC5jb20v
Decoded URL: https://techiedelight.com/

 
To encode a large block of text using the MIME encoder, use getMimeEncoder() and getMimeDecoder() functions.

Download Code

Output (may vary):

e2317f97-47d0-4799-b383-2a89070d5c1ef57d1659-3153-47d6-88a1-be3d5cca8cf526afb83c-c0db-4ef6-bd41-edc7ca4a691db744a484-f6fd-4f80-a7e4-4d8d3d7d3153309b3b8c-d4b3-4027-821b-85450c735616

2. Using DatatypeConverter class

The DatatypeConverter class provides printBase64Binary() and parseBase64Binary() functions, which can be used to convert an array of bytes into a string and vice-versa.

Download Code

Output:

Encoded String: U29tZSB0ZXh0
Decoded String: Some text

That’s all about base64 encoding and decoding in Kotlin.