In this tutorial, I will show you how to make Base64 encoding and decoding functionality in Kotlin/Android. We’re gonna convert several kinds of String to Base64, then decode Base64 to original String.
Contents
Overview
This is step by step to encode and decode with Kotlin Base64.
– Encoding (convert String to Base64):
- convert String to
ByteArray
using toByteArray() method - call encode method (depending on library) to get Base64 String from
ByteArray
above
– Decoding (convert Base64 to String):
- retrieve
ByteArray
from Base64 String using decode method (depending on library) - convert the
ByteArray
into String object using String constructor
We’re gonna import one of these libraries that support Base64
Encoding and Decoding:
Let’s implement these steps with the libraries in the next sections.
Using java.util.Base64
This library supports the following types of Base64 as specified in RFC 4648 and RFC 2045:
- Basic
- URL and Filename safe
- MIME
– Uses “The Base64 Alphabet” as specified in Table 1 of RFC 4648 and RFC 2045 for encoding and decoding operation.
– Encoding: not add any line feed (line separator) character.
– Decoding: not contain characters outside the Base64 Alphabet.
– Uses the “URL and Filename safe Base64 Alphabet” as specified in Table 2 of RFC 4648 for encoding and decoding.
– Encoding: not add any line feed (line separator) character.
– Decoding: not contain characters outside the Base64 Alphabet.
– Uses the “The Base64 Alphabet” as specified in Table 1 of RFC 2045 for encoding and decoding operation.
– Encoding: result must be represented in lines of no more than 76 characters each and use a carriage return followed by a linefeed (\r\n). No line separator is added to the end.
– Decoding: not contain line separators or other characters outside the Base64 Alphabet.
Basic Base64 encode
– Step by step to encode:
- get
ByteArray
from original String usingtoByteArray()
method - use Base64.getEncoder() static method to get Encoder that encodes using the Basic type Base64 encoding scheme
- call Encoder encodeToString() method on
ByteArray
above
package com.bezkoder.kotlin.base64
import java.util.Base64
fun main(args: Array<String>) {
val oriString = "bezkoder tutorial"
val encodedString: String = Base64.getEncoder().encodeToString(oriString.toByteArray())
println(encodedString)
}
Result:
YmV6a29kZXIgdHV0b3JpYWw=
– Step by step to decode:
- use Base64.getDecoder() to get Decoder that decodes using the Basic type base64 encoding scheme.
- call decode() method that returns a
ByteArray
- use constructor of the String class on
ByteArray
above to get String result
val decodedBytes = Base64.getDecoder().decode(encodedString)
val decodedString = String(decodedBytes)
println(decodedString)
Output:
bezkoder tutorial
Base64 encode without Padding
In Base64 encoding, the length of output encoded String must be a multiple of 3. If it’s not, pad characters (‘=’) will be added to the output.
For more details about padding in Base64, please visit the answer on StackOverflow.
To encode Base64 without padding, we call withoutPadding() that returns an encoder instance that encodes without adding any padding character at the end of the encoded byte data.
package com.bezkoder.kotlin.base64
import java.util.Base64
fun main(args: Array<String>) {
val oriString = "bezkoder tutorial"
val encodedString =
Base64.getEncoder().withoutPadding().encodeToString(oriString.toByteArray())
println(encodedString)
val decodedBytes = Base64.getDecoder().decode(encodedString)
val decodedString = String(decodedBytes)
println(decodedString)
}
Result:
YmV6a29kZXIgdHV0b3JpYWw
bezkoder tutorial
Base64 encode Url
URL encoding uses the URL and Filename safe Base64. It is similar to the basic encoder above.
– Step by step to encode:
- get
ByteArray
from original Url usingtoByteArray()
method - use Base64.getUrlEncoder() static method to get Encoder that encodes using the URL and Filename safe type base64 encoding scheme
- call Encoder encodeToString() method on
ByteArray
above
package com.bezkoder.kotlin.base64
import java.util.Base64
fun main(args: Array<String>) {
val oriUrl = "https://www.bezkoder.com/?abc=xyz"
val encodedUrl = Base64.getUrlEncoder().encodeToString(oriUrl.toByteArray())
println(encodedUrl)
}
Output:
aHR0cHM6Ly93d3cuYmV6a29kZXIuY29tLz9hYmM9eHl6
– Step by step to decode:
- use Base64.getUrlDecoder() to get Decoder that decodes using the URL and Filename safe type base64 encoding scheme
- call decode() method that returns a
ByteArray
- use constructor of the String class on
ByteArray
above to get String result
val decodedUrlBytes = Base64.getUrlDecoder().decode(encodedUrl)
val decodedUrl = String(decodedUrlBytes)
println(decodedUrl)
Result:
https://www.bezkoder.com/?abc=xyz
Base64 encode MIME
The MIME encoder generates a Base64 encoded output but in a MIME friendly format.
Now we create a function to generate a MIME buffer for test:
import java.util.UUID
fun generateMimeBuffer(): StringBuilder {
val buffer = StringBuilder()
for (i in 0 until 10) {
buffer.append(UUID.randomUUID().toString())
}
return buffer;
}
– Step by step to encode:
- get
ByteArray
from original MIME buffer usingtoString()
&toByteArray()
method - use Base64.getMimeEncoder() static method to get Encoder that encodes using the MIME type base64 encoding scheme
- call Encoder encodeToString() method on
ByteArray
above
package com.bezkoder.kotlin.base64
import java.util.Base64
fun main(args: Array<String>) {
val buffer: StringBuilder = generateMimeBuffer()
println("> buffer:\n" + buffer)
val encodedAsBytes = buffer.toString().toByteArray()
val encodedMime = Base64.getMimeEncoder().encodeToString(encodedAsBytes)
println("> encodedMime:\n" + encodedMime)
}
Output:
> buffer:
b49c8005-4426-40a8-9a6e-b93ab2acb3a00f5dd3ce-1add-4956-984c-e9e7119eb9c10199f8b3-f984-43c4-bf43-26d2b4412740503350d3-676b-42cd-aa7d-4cb80c4e9f653520cfcb-d985-4540-9745-b333d6ebc30f8a22d993-0357-4ebe-8d33-2ed1932881dec4e54fd1-eca7-4db1-85b4-d5de03fd31f9c88c0cca-55a5-4bc6-a032-5f1beb6e3f19e65cbb40-9ac3-4702-9994-55ab37b61e0cebe1af66-89a3-4fc3-a9b1-949b2d5463dd
> encodedMime:
YjQ5YzgwMDUtNDQyNi00MGE4LTlhNmUtYjkzYWIyYWNiM2EwMGY1ZGQzY2UtMWFkZC00OTU2LTk4
NGMtZTllNzExOWViOWMxMDE5OWY4YjMtZjk4NC00M2M0LWJmNDMtMjZkMmI0NDEyNzQwNTAzMzUw
ZDMtNjc2Yi00MmNkLWFhN2QtNGNiODBjNGU5ZjY1MzUyMGNmY2ItZDk4NS00NTQwLTk3NDUtYjMz
M2Q2ZWJjMzBmOGEyMmQ5OTMtMDM1Ny00ZWJlLThkMzMtMmVkMTkzMjg4MWRlYzRlNTRmZDEtZWNh
Ny00ZGIxLTg1YjQtZDVkZTAzZmQzMWY5Yzg4YzBjY2EtNTVhNS00YmM2LWEwMzItNWYxYmViNmUz
ZjE5ZTY1Y2JiNDAtOWFjMy00NzAyLTk5OTQtNTVhYjM3YjYxZTBjZWJlMWFmNjYtODlhMy00ZmMz
LWE5YjEtOTQ5YjJkNTQ2M2Rk
– Step by step to decode:
- use Base64.getMimeDecoder() to get Decoder that decodes using the MIME type base64 decoding scheme.
- call decode() method that returns a
ByteArray
- use constructor of the String class on
ByteArray
above to get String result
val decodedMimeBytes = Base64.getMimeDecoder().decode(encodedMime)
val decodedMime = String(decodedMimeBytes)
println(decodedMime)
Result:
b49c8005-4426-40a8-9a6e-b93ab2acb3a00f5dd3ce-1add-4956-984c-e9e7119eb9c10199f8b3-f984-43c4-bf43-26d2b4412740503350d3-676b-42cd-aa7d-4cb80c4e9f653520cfcb-d985-4540-9745-b333d6ebc30f8a22d993-0357-4ebe-8d33-2ed1932881dec4e54fd1-eca7-4db1-85b4-d5de03fd31f9c88c0cca-55a5-4bc6-a032-5f1beb6e3f19e65cbb40-9ac3-4702-9994-55ab37b61e0cebe1af66-89a3-4fc3-a9b1-949b2d5463dd
Using javax DatatypeConverter
– Step by step to encode:
- get
ByteArray
from original MIME buffer usingtoString()
&toByteArray()
method - use DatatypeConverter.printBase64Binary() method on
ByteArray
above
package com.bezkoder.kotlin.base64
import javax.xml.bind.DatatypeConverter
fun main(args: Array<String>) {
val oriString = "bezkoder tutorial"
val encodedString = DatatypeConverter.printBase64Binary(oriString.toByteArray())
println(encodedString)
}
Output:
YmV6a29kZXIgdHV0b3JpYWw=
– Step by step to decode:
- call DatatypeConverter.parseBase64Binary() method that returns a
ByteArray
- use constructor of the String class on
ByteArray
above to get String result
val decodedBytes = DatatypeConverter.parseBase64Binary(encodedString)
val decodedString = String(decodedBytes)
println(decodedString)
Result:
bezkoder tutorial
Using Apache Commons Codec
First we need to add Apache Commons Codec library to our Kotlin project.
There are two ways:
- Add dependency to pom.xml
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.14</version>
</dependency>
The latest version of this library can be found at:
https://mvnrepository.com/artifact/commons-codec/commons-codec
we’re gonna import org.apache.commons.codec.binary.Base64
class. Depending on the constructor, we can create Base64 object with different purpose and usage:
Base64(boolean urlSafe)
: URL safe mode (default isoff
).Base64(int lineLength)
: URL unsafe mode with the length of the line (default is76
)Base64(int lineLength, byte[] lineSeparator)
: with line separator (default is CRLF"\r\n"
)
– Step by step to encode:
- get
ByteArray
from original MIME buffer usingtoString()
&toByteArray()
method - use contructor method to get Base64 object
- call
encode()
method onByteArray
above
package com.bezkoder.kotlin.base64
import org.apache.commons.codec.binary.Base64
fun main(args: Array<String>) {
val originalInput = "bezkoder tutorial"
val base64: Base64 = Base64()
val encodedStr = String(base64.encode(originalInput.toByteArray()))
println(encodedStr)
}
Output:
YmV6a29kZXIgdHV0b3JpYWw=
If we use val base64 = Base64(8)
, the result will be like this-
YmV6a29k
ZXIgdHV0
b3JpYWw=
– Step by step to decode:
- call
decode()
method that returns aByteArray
- get String result using constructor of the String class on
ByteArray
above
val decodedBytes = base64.decode(encodedStr)
val decodedString = String(decodedBytes)
println(decodedString)
Result:
bezkoder tutorial
Conclusion
Today we’ve known way to do Base64 encoding and decoding in Kotlin using using java.util.Base64, javax.xml.bind.DatatypeConverter or Apache Commons Codec utility APIs.
Happy Learning! See you again.
Superb, what a web site it is! This tutorial provides valuable Kotlin practice to us, keep it up.
I’m still new to the whole Kotlin stuff and you make everything easy for me! Thanks!
Many thanks!!
Thank you for the good tutorial.
Highly descriptive Kotlin basics article, I loved that a lot. Thanks!
Thanks a lot for the tutorial!
Many thanks for the tutorial.
GREAT!!!! Thanks!