cybersecurity · intermediate · ~15 min

Bounded base64 decoder

Bounds-safe base64 decoding with strict validation.

Challenge

Your job

#include <stdint.h>
#include <stddef.h>
int b64_decode(const char *in, uint8_t *out, size_t cap);

Decode standard base64 in into out (max cap bytes). Return the number of bytes written, or -1 on: NULL input, length not a multiple of 4, an invalid character, padding (=) before the end, or an overflow of cap.

Hints

  1. Map each char to its 6-bit value; = is padding.
  2. Every 4 input chars → 3 output bytes (minus the padding count).
  3. Check out capacity BEFORE writing each byte.

Why this matters

Base64 is everywhere in security tooling — tokens, certs, payloads. A bounded decoder that rejects bad input is the safe foundation.

Starter code

#include <stdint.h>
#include <stddef.h>
int b64_decode(const char *in, uint8_t *out, size_t cap) {
    /* TODO */
    (void)in; (void)out; (void)cap;
    return -1;
}

Common mistakes

Not rejecting length % 4 != 0. Allowing data after padding. Writing past cap.

Edge cases to handle

Empty string → 0. One/two '=' padding. Overflow into a tiny buffer.

Complexity

O(n).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.