Secure Coding in C · beginner · ~12 min

Score a password against a policy (defensive)

Validate that a candidate password meets a minimum length + character-class policy.

Overview

Per-character pass over the password, tally has_upper / has_lower / has_digit / has_special, compare length, return a bitmask of failed requirements.

Why it matters

Password policy is the cheapest, simplest, most defensive layer in any auth stack. Five lines stop most brute-force entirely.

Lesson

Why this matters

The defensive answer to "how do we stop brute-force?" is rarely "build a faster password cracker". It's "enforce a sensible password policy at registration / change time".

This exercise teaches the validator side: given a candidate password and a policy struct, decide whether the password is acceptable. No hashing, no cracking, no online tests. Pure string + character-class logic.

What the policy looks like

typedef struct {
    int min_length;          // e.g. 12
    int require_upper;       // boolean
    int require_lower;       // boolean
    int require_digit;       // boolean
    int require_special;     // boolean
} pw_policy_t;

Your job

Implement int pw_check(const char *pw, const pw_policy_t *p) that returns:

  • 0 — meets all required classes + length
  • non-zero — fails one or more requirements (each bit position represents which requirement failed; OR-of-bits is fine)

Common mistakes

  • Reading past the NUL. Use strnlen(pw, MAX) if you want a hard cap.
  • Treating 'A'..'Z' ranges as locale-independent. They are in C with unsigned char casts; that's fine here.
  • Returning 1 for every failure. The harness expects distinct bits so the caller knows which class is missing.

Summary

Pure local validation. No hashing, no network. Each requirement is one boolean; combine with the length check; return a bitmask of failures.

Practice with these exercises