cybersecurity · intermediate · ~15 min
Bounds-safe base64 decoding with strict validation.
#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.
= is padding.out capacity BEFORE writing each byte.Base64 is everywhere in security tooling — tokens, certs, payloads. A bounded decoder that rejects bad input is the safe foundation.
#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;
}
Not rejecting length % 4 != 0. Allowing data after padding. Writing past cap.
Empty string → 0. One/two '=' padding. Overflow into a tiny buffer.
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.