Parse Token Components Without External Libraries
StringsAuto-graded · 13 test casesLast 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
- Split the input string on
.to extract three segments - Decode the first segment (header) from Base64URL to a JSON string
- Decode the second segment (payload) from Base64URL to a JSON string
- Parse both JSON strings into objects
- 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A three-part token string has the structure base64url(header).base64url(payload).base64url(signature). To decode it, we need to:
- Split the string on periods to isolate the three segments
- Manually decode Base64URL for the first two segments
- Parse the resulting JSON strings into Python dictionaries
- Return both in a single dictionary with
"header"and"payload"keys
The core challenge is implementing Base64URL decoding without libraries.
Base64URL Decoding Algorithm
Base64URL represents binary data as text by encoding every 6 bits as one character from a 64-character alphabet. To decode:
- Build a mapping from each character to its 6-bit value (0-63)
- Process characters left to right, accumulating bits:
- Shift the accumulator left by 6 bits
- OR in the new character's value
- Track how many bits are in the accumulator
- Whenever 8+ bits are available:
- Extract the top 8 bits as a byte
- Append the byte to output
- Reduce the bit count by 8
- Discard any remaining bits (less than 8) at the end
This streaming approach handles segments of any length. When the length isn't divisible by 4, the final group contains padding bits (2 or 4 bits) that are automatically discarded because they never reach 8 bits.
Why It Works
Base64 packs 3 bytes (24 bits) into 4 characters (4 × 6 = 24 bits). Reading characters sequentially and emitting bytes as soon as 8 bits accumulate reconstructs the original byte sequence in order.
The padding-free nature of Base64URL is handled naturally: leftover bits at the end are zero-fill padding from the encoder and carry no information, so dropping them is correct.
After decoding bytes, we interpret them as UTF-8 text and parse the JSON.
Complexity
- Time: O(n) where n is the token length. Each character is processed once, and JSON parsing is linear in decoded size.
- Space: O(n) for the decoded byte buffers and parsed objects.
Solution
import json
from typing import Dict
def _decode_base64url(encoded: str) -> str:
"""Decode a Base64URL string to UTF-8 text."""
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
char_to_value = {char: i for i, char in enumerate(alphabet)}
bits = 0
bit_count = 0
output = bytearray()
for char in encoded:
bits = (bits << 6) | char_to_value[char]
bit_count += 6
if bit_count >= 8:
bit_count -= 8
output.append((bits >> bit_count) & 0xFF)
return output.decode("utf-8")
def parse_token(token: str) -> Dict[str, object]:
first_part, second_part, _third_part = token.split(".")
header = json.loads(_decode_base64url(first_part))
payload = json.loads(_decode_base64url(second_part))
return {"header": header, "payload": payload}