Skip to content
This repository has been archived by the owner on Jul 8, 2022. It is now read-only.

Commit

Permalink
Fixes Base64 decode when no padding is provided (#37)
Browse files Browse the repository at this point in the history
* Add tests from Korio + add test reproducing and fixing the issue #64

* Fixes Base64 decoding when no padding is provided
  • Loading branch information
soywiz authored Nov 27, 2020
1 parent 5e616c6 commit 96901ac
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ object Base64 {
continue // skip character
}

val b0 = DECODE[src.readU8(n++)]
val b1 = DECODE[src.readU8(n++)]
val b2 = DECODE[src.readU8(n++)]
val b3 = DECODE[src.readU8(n++)]
val b0 = if (n < src.size) DECODE[src.readU8(n++)] else 64
val b1 = if (n < src.size) DECODE[src.readU8(n++)] else 64
val b2 = if (n < src.size) DECODE[src.readU8(n++)] else 64
val b3 = if (n < src.size) DECODE[src.readU8(n++)] else 64
dst[m++] = (b0 shl 2 or (b1 shr 4)).toByte()
if (b2 < 64) {
dst[m++] = (b1 shl 4 or (b2 shr 2)).toByte()
Expand Down
45 changes: 45 additions & 0 deletions krypto/src/commonTest/kotlin/com/soywiz/krypto/Base64Test.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.soywiz.krypto

import com.soywiz.krypto.encoding.Base64
import com.soywiz.krypto.encoding.fromBase64
import com.soywiz.krypto.encoding.toBase64
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class Base64Test {
@Test
fun name() {
assertEquals("AQID", Base64.encode(byteArrayOf(1, 2, 3)))
assertEquals("aGVsbG8=", Base64.encode("hello".encodeToByteArray()))
assertEquals(byteArrayOf(1, 2, 3).toList(), Base64.decode("AQID").toList())
assertEquals("hello", Base64.decode("aGVsbG8=").decodeToString())
}

@Test
fun testSeveral() {
for (item in listOf("", "a", "aa", "aaa", "aaaa", "aaaaa", "Hello World!")) {
assertEquals(item, item.encodeToByteArray().toBase64().fromBase64().decodeToString())
}
}

@Test
fun testGlobal() {
assertEquals("hello", globalBase64)
assertEquals("hello", ObjectBase64.globalBase64)
}

@Test
fun testIssue64DecodeWithMissingPadding() {
assertEquals(
"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ==",
Base64.encode(Base64.decode("eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"))
)
}
}

object ObjectBase64 {
val globalBase64 = "aGVsbG8=".fromBase64().decodeToString()
}

val globalBase64 = "aGVsbG8=".fromBase64().decodeToString()

0 comments on commit 96901ac

Please sign in to comment.