Mime

Common
JVM
JS
Native
1.0
val Mime: Base64
(source)

The encoding specified by RFC 2045 section 6.8, Base64 Content-Transfer-Encoding.

Uses "The Base64 Alphabet" as specified in Table 1 of RFC 2045 for encoding and decoding, consisting of 'A'..'Z', 'a'..'z', '+' and '/' characters.

This instance is configured with the padding option set to PaddingOption.PRESENT. Use the withPadding function to create a new instance with a different padding option if necessary.

Encode operation adds CRLF every 76 symbols. No line separator is added to the end of the encoded output. Decode operation ignores all line separators and other characters outside the base64 alphabet.

import kotlin.io.encoding.*
import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val encoded = Base64.Mime.encode("Hello? :> ".encodeToByteArray())
println(encoded) // SGVsbG8/IDo+IA==

// Mime encoding ignores all characters not belonging to its alphabet
val decoded = Base64.Mime.decode("Y@{mFz!Z!TY}0")
println(decoded.decodeToString()) // base64

// let's encode some long text
val sourceText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " +
        "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +
        "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris " +
        "nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in " +
        "reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla " +
        "pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa" +
        " qui officia deserunt mollit anim id est laborum."

// each line consists of 76 characters
val expectedText = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwg\r\n" +
        "c2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWdu\r\n" +
        "YSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0\r\n" +
        "aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1\r\n" +
        "YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2\r\n" +
        "ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRl\r\n" +
        "dXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1\r\n" +
        "aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg=="

println("Base64.Mime.encode(sourceText.encodeToByteArray()).contentEquals(expectedText) is ${Base64.Mime.encode(sourceText.encodeToByteArray()).contentEquals(expectedText)}") // true
//sampleEnd
}