PRESENT_OPTIONAL

Pad on encode, allow optional padding on decode.

When encoding, the result is padded with '=' to reach an integral multiple of 4 symbols. When decoding, the input may be either padded or unpadded. If the input contains a padding character, the correct amount of padding character(s) must be present. The padding character '=' marks the end of the encoded data, and subsequent symbols are prohibited.

Samples

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

fun main() { 
   //sampleStart 
   val format = HexFormat { upperCase = true; bytes.byteSeparator = " " }
val bytes = byteArrayOf(0xDE.toByte(), 0x2D, 0x02, 0xC0.toByte())

val base64PresentOptionalPadding = Base64.Default.withPadding(Base64.PaddingOption.PRESENT_OPTIONAL)

// PaddingOption.PRESENT_OPTIONAL pads on encode
println(base64PresentOptionalPadding.encode(bytes)) // 3i0CwA==
// It allows both padded and unpadded decode inputs
println(base64PresentOptionalPadding.decode("3i0CwA==").toHexString(format)) // DE 2D 02 C0
println(base64PresentOptionalPadding.decode("3i0CwA").toHexString(format)) // DE 2D 02 C0
// However, partially padded input is prohibited
// base64PresentOptionalPadding.decode("3i0CwA=") // will fail with IllegalArgumentException 
   //sampleEnd
}

Properties

Link copied to clipboard
Link copied to clipboard