KatInterview

Parse Token Components Without External Libraries

StringsAuto-graded · 13 test cases
HardAuto-gradedStringsencodingparsingbit-manipulation

Last updated

Tests manual implementation of Base64URL decoding and understanding of multi-part token structure with bit-level encoding.

Problem Statement

You are given a string representing a three-part token where each part is separated by a period (.). The first two parts are encoded using a variant of Base64 called Base64URL, and the third part can be ignored.

Your task is to decode the first two parts and return them as a dictionary with keys "header" and "payload". Each decoded part is a JSON object.

Base64URL encoding differences from standard Base64:

  • Uses - instead of +
  • Uses _ instead of /
  • Omits trailing = padding characters

You must implement the Base64URL decoding logic yourself without using any Base64 decoding libraries. You may use standard JSON parsing functions.

Decoding Steps

  1. Split the input string on . to extract three segments
  2. Decode the first segment (header) from Base64URL to a JSON string
  3. Decode the second segment (payload) from Base64URL to a JSON string
  4. Parse both JSON strings into objects
  5. Return a dictionary containing both decoded objects

Base64URL Character Set

Base64URL uses 64 characters to encode 6 bits each:

  • A-Z (indices 0-25)
  • a-z (indices 26-51)
  • 0-9 (indices 52-61)
  • - (index 62)
  • _ (index 63)

Each character represents a 6-bit value. Decoding converts groups of these characters back into 8-bit bytes.

Constraints

  • The input is a validly formatted three-segment token string
  • Token length: up to 10,000 characters
  • Both decoded parts will be valid UTF-8 encoded JSON
  • You must implement Base64URL decoding manually
  • You may use standard library JSON parsing

Return Format

{
    "header": { ... },  # decoded first segment
    "payload": { ... }  # decoded second segment
}

Examples

Example 1

Input: parse_token('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.signature')

Output: {'header': {'alg': 'HS256', 'typ': 'JWT'}, 'payload': {'sub': '1234567890', 'name': 'John Doe'}}

Hints

Hint 1

Each Base64URL character encodes exactly 6 bits of information. Accumulate these bits and emit bytes whenever you have 8 or more bits available.

Hint 2

Map each character to its 6-bit value (0-63), shift it into a bit accumulator, and extract complete bytes from the accumulator as you go.

Hint 3

The segment length may not be divisible by 4. Any leftover bits at the end (less than 8) should be discarded—they represent padding and contain no data.