Cryptography Foundations

Last update: 2026-09-03 15:56:39 +0800 +0800
Available translations: 日本語 / 中文(简体) / 中文(繁體)

Cryptography applies mathematical primitives to security goals such as confidentiality, integrity, peer authentication, and non-repudiation. A secure primitive does not make a protocol secure by itself because encodings, key management, randomness, state, and the attacker’s capabilities also determine the result.

Bits, XOR, and Modular Arithmetic #

Cryptographic specifications operate on precisely sized bit strings and byte strings. Exclusive-or is addition modulo two:

aba XOR b
000
011
101
110

XOR is associative, commutative, and self-inverse, so (message XOR mask) XOR mask = message. Those identities explain how a stream cipher applies and removes a keystream. They do not imply security: repeating the mask exposes relationships between plaintexts.

Modular arithmetic groups integers into congruence classes. The notation a ≡ b (mod n) means that n divides a - b. Addition and multiplication remain within those classes. An integer a has a multiplicative inverse modulo n exactly when gcd(a, n) = 1; the extended Euclidean algorithm finds that inverse.

Prime moduli produce finite fields in which every nonzero element is invertible. Other public-key systems operate in carefully selected finite groups, including elliptic-curve groups. Implementations must use the group, encoding, validation, and subgroup rules defined by the selected standard rather than treating arbitrary integers or points as valid keys.

Probability and Security Parameters #

Cryptographic guarantees are probabilistic and parameterized. If a secret is uniformly sampled from 2^k possibilities, exhaustive search takes approximately 2^(k-1) guesses on average. An ideal n-bit hash requires about 2^n work for a preimage but only 2^(n/2) work for a collision because of the birthday bound.

A security parameter states the intended work factor, not the number of bits in every object. A 256-bit elliptic-curve group can target about 128-bit classical security, while a 256-bit hash targets 256-bit preimage resistance and 128-bit collision resistance. Algorithm-specific attacks, quantum attack models, implementation leakage, weak random generation, and key lifetime can reduce the effective strength. Parameter selection must therefore follow the protocol standard and current key-management guidance.

Probabilities also govern failure limits. Authentication tags can be forged with some bounded probability, and nonce-based modes cap the number and total size of messages processed under one key. Systems must enforce those usage limits rather than assuming that a large key alone makes unlimited use safe.

One-Time Pads and Stream Ciphers #

For equal-length strings, a one-time pad computes:

text
ciphertext = plaintext XOR pad
plaintext  = ciphertext XOR pad

Information-theoretic secrecy holds only when the pad is uniformly random, secret, at least as long as the plaintext, and never reused in whole or in part. Reusing a pad gives ciphertext1 XOR ciphertext2 = plaintext1 XOR plaintext2, which leaks structure even if neither plaintext is initially known. Generating, distributing, and destroying pads safely makes the construction impractical for most software systems.

A stream cipher replaces the truly random pad with a pseudorandom keystream derived from a compact secret key and a nonce. The nonce is normally public, but its uniqueness requirement is mandatory. Repeating a nonce under one ChaCha20-Poly1305 key repeats the ChaCha20 keystream and also reuses the one-time authentication key. AES-GCM likewise loses strong confidentiality and authentication guarantees after nonce reuse. Use a library API that manages or validates nonces, and rotate the key before the mode’s message or data limits.

Authenticated Encryption and Associated Data #

Encryption alone does not detect modification. An authenticated-encryption with associated data (AEAD) scheme returns ciphertext and an authentication tag while authenticating:

  • the plaintext, which remains confidential;
  • associated data, which remains visible but cannot be changed unnoticed; and
  • the nonce and algorithm inputs as required by the scheme.

Headers such as protocol versions, record sequence numbers, tenant identifiers, or routing fields can be associated data when intermediaries must read them. Both endpoints must serialize exactly the same associated data because a difference makes tag verification fail.

Use a standardized AEAD such as AES-GCM or ChaCha20-Poly1305 through a maintained cryptographic library. The receiver must not release or act on unauthenticated plaintext. A failed tag is an authentication failure; retries, logs, and error responses must not reveal partial plaintext or distinguish useful internal failure states. An unkeyed digest appended to ciphertext does not provide this protection.

Hashes, MACs, and Key Derivation #

Related-looking primitives have distinct roles:

PrimitiveSecret InputPrimary Role
Cryptographic hashNoStable digest, commitment component, or protocol-defined transcript hash
Message authentication code (MAC)Shared keyIntegrity and source authentication among key holders
Key-derivation function (KDF)Secret keying materialProduce context-bound keys with the required length
Password-hashing functionPassword and saltMake offline password guesses costly

A plain hash cannot authenticate data because an attacker who replaces a message can calculate its new digest. HMAC is a standardized MAC construction; do not substitute hash(key || message). HKDF first extracts a fixed-length pseudorandom key from input keying material and then expands it into context-specific output. Its salt and info inputs are not passwords and serve different purposes from a password hash’s per-account random salt.

KDF context labels separate keys by protocol, version, direction, role, and purpose. For example, an encryption key and a MAC key must not be the same bytes merely because both came from one shared secret. Follow the enclosing protocol’s defined labels and encoding because ambiguous concatenation defeats that separation.

Asymmetric Key Establishment and Signatures #

Diffie-Hellman and elliptic-curve Diffie-Hellman let two parties derive a shared secret across an observable channel. Bare Diffie-Hellman does not authenticate either party: an active attacker can negotiate one secret with each endpoint. A complete protocol binds the exchange transcript to certificates, pre-shared keys, or previously authenticated public keys, then derives traffic keys with a KDF.

A key encapsulation mechanism (KEM) produces a shared secret and an encapsulation for a recipient’s public key. Protocols may combine independently secure components during a cryptographic migration, but the combination and its KDF must come from a reviewed protocol specification. Public-key encryption is not interchangeable with key agreement or a KEM.

Digital signatures bind a private signing operation to a message and allow verification with the public key. Algorithms such as Ed25519, ECDSA, and RSA-PSS define message formatting, hashing, randomness or deterministic nonce generation, and verification rules. A signature is not “encryption with the private key,” and signature verification does not make an untrusted public key authentic.

Start with a Threat Model #

Select primitives only after stating the security boundary:

  1. Identify protected assets and whether confidentiality, integrity, peer authentication, replay resistance, or forward secrecy is required.
  2. Identify attacker capabilities, including observation, active modification, chosen inputs, endpoint compromise, side channels, rollback, and denial of service.
  3. Define trust anchors, key ownership, key rotation, compromise recovery, and authenticated metadata.
  4. Choose a standardized protocol and maintained implementation whose security properties match those requirements.

TLS can protect data in transit while leaving compromised endpoints, authorization errors, and application-level replay outside its boundary. Signatures can prove that a key authorized a message while saying nothing about whether that key should be trusted. Explicit boundaries prevent one property from being mistaken for another.

OpenSSH randomart illustrates the same distinction. It is a visual rendering of a public-key fingerprint, not an authenticated identity proof. Compare the full fingerprint over a separately authenticated channel.

References #

Comments

Read or comment on GitHub (sign-in required to comment)