cybersecurity · beginner · ~15 min
Strict allow-list + length validation in a single pass.
Implement int valid_token(const char *s, size_t min_len, size_t max_len).
Return 1 if all of the following hold:
s is non-NULL.strlen(s) is in [min_len, max_len].s is in the allow-list [A-Za-z0-9_-].Return 0 otherwise.
valid_token("abc123_XYZ-99", 8, 32) -> 1
valid_token("short", 8, 32) -> 0 // too short
valid_token("has space here", 1, 64)-> 0 // space not allowed
valid_token("ok!", 1, 64) -> 0 // ! not allowed
valid_token("", 0, 64) -> 1 // empty allowed when min == 0
valid_token(NULL, 0, 64) -> 0
API keys, session tokens, and CSRF cookies look random to humans but follow strict rules (e.g. [A-Za-z0-9_-], 32-64 bytes). Validating that a token only contains allow-listed characters before passing it on to anything else is the cheapest defence against injection.
String + length window.
1/0.
Single pass; no allocations.
#include <stddef.h>
int valid_token(const char *s, size_t min_len, size_t max_len) { /* TODO */ return 0; }
Deny-listing (if (c == ';') return 0;) — infinite holes. Forgetting NULL guard.
Empty input with min==0; min > max; NULL pointer.
O(strlen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.