Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 147 ยท Security

Hashing, Encryption and Random Numbers

Practical cryptography in PHP - hash and hash_hmac, secure random numbers, the Random\Randomizer API, encryption with sodium and OpenSSL, and what not to build.

Cryptography shows up in everyday PHP code more often than you'd think: a checksum for an uploaded file, a token in a password-reset link, a signature on a webhook, an encrypted API key in the database, a shuffled quiz. Each of these needs a different tool, and picking the wrong one, such as md5() for a signature or rand() for a token, creates holes that are invisible until someone exploits them.

This lesson is a practical map rather than a math course. You'll learn the difference between hashing, message authentication and encryption; how to get secure random numbers with random_bytes(), random_int() and the Random\Randomizer class (PHP 8.2); how to encrypt data with the sodium extension or OpenSSL's AES-GCM; and, just as important, which things you should never build yourself.

Passwords are a special case with their own lesson: Password Hashing. The general rules come from Web Security Basics.

Three different jobs

Job Question it answers PHP tool Reversible?
Hashing "Is this data exactly the same as before?" hash('sha256', $data) No
Message authentication (MAC) "Did someone who knows the secret key create this, unchanged?" hash_hmac('sha256', $data, $key) No
Encryption "Can only key holders read this?" sodium_crypto_secretbox(), openssl_encrypt() with AES-GCM Yes, with the key
Password hashing "Is this the right password?" (slowly, with a salt) password_hash() No

Mixing these up is the most common mistake. A plain hash proves nothing about who made the data, since anyone can compute it. Encryption without authentication lets attackers modify ciphertext. And encrypting passwords is wrong, because whoever has the key can read them all.

Hashing with hash()

hash($algorithm, $data) returns a hex fingerprint of any string. The same input always gives the same output, and a tiny change in the input changes the whole hash. PHP supports dozens of algorithms (hash_algos() lists them). Use the SHA-2 family (sha256, sha512) or SHA-3 (sha3-256) when security matters; md5 and sha1 are broken for that (attackers can create two different inputs with the same hash) and survive only for compatibility. For non-security uses like cache keys, the very fast xxHash algorithms (xxh3, xxh128) are ideal.

PHP Fingerprints with hash()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Changing one digit in the invoice produces a completely different hash in every algorithm. hash_file() reads the file in chunks, so it works for gigabyte files, and hash_init()/hash_update()/hash_final() do the same for streamed data. Publishing the SHA-256 of a download lets users verify that it wasn't corrupted, though only if the hash itself comes from a trusted place.

Signing data with hash_hmac

When the receiver must know that a message came from someone who holds a secret key, you need a MAC. hash_hmac('sha256', $message, $key) computes an HMAC, a construction that mixes the key into the hash in a way that's safe to use. Typical uses:

  • Webhooks: a payment provider signs each request body, and you check the signature before trusting it.
  • Signed URLs: a download link that expires, where users can't change the file name or the expiry time.
  • Tamper-proof cookies or tokens: data the client stores but must not modify.
PHP Signed URLs with hash_hmac

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Any change to the path or the expiry time invalidates the signature, and the valid link stops working once it expires. As in Preventing CSRF, the comparison uses hash_equals() so the check takes the same time no matter how many characters match.

Don't build a MAC as hash('sha256', $key . $message). SHA-256 and SHA-512 allow a length-extension attack on that construction: knowing the hash of key + message, an attacker can compute a valid hash for key + message + extra data without the key. HMAC is designed to prevent this, so always use hash_hmac().

To turn one master secret into several independent keys (one for signing, one for encryption), use hash_hkdf('sha256', $masterKey, 32, 'purpose-name'). Never reuse the same key for different jobs.

Secure random numbers

Tokens, keys, salts, nonces and codes must be unpredictable. PHP has two kinds of randomness:

  • Cryptographically secure: random_bytes(), random_int(), and Random\Randomizer with its default engine. They read from the operating system's secure generator. Use them for anything security related.
  • Not secure: rand(), mt_rand(), shuffle(), str_shuffle(), array_rand(), uniqid() and lcg_value() (deprecated in 8.4). They use the Mersenne Twister or the clock; after observing some outputs, an attacker can predict the rest. They're fine for games and sampling, never for secrets.

The danger is easy to see with a seed. mt_rand() is deterministic: the same seed always gives the same sequence. Older PHP code sometimes seeded it with the time, which an attacker can guess:

PHP Predictable and unpredictable random numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The weak code is reproduced instantly, whatever value it has on a given run. The secure lines print different values on every run, and there's no seed to guess. As a rule of thumb, 16 bytes (128 bits) is enough for any token, 32 bytes for keys. The base64url form (with - and _ instead of + and /, no = padding) is shorter than hex and safe in URLs.

The Random\Randomizer API (PHP 8.2+)

PHP 8.2 introduced the Random extension with an object-oriented API. A Random\Randomizer wraps an engine; the default engine, Random\Engine\Secure, is cryptographically secure. It covers the jobs the old functions did, without their pitfalls:

PHP Random numbers with Randomizer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

getBytesFromString() (PHP 8.3) builds codes from your own alphabet; this one leaves out easily confused characters like 0/O and 1/I. nextFloat() and getFloat() (8.3) produce correctly distributed floats, which mt_rand() / mt_getrandmax() doesn't. The two seeded randomizers print the same three numbers, which is useful for reproducible tests and simulations. Other engines are Mt19937 (compatible with mt_rand()) and PcgOneseq128XslRr64.

Encryption

Encryption is for data you need to read again: an API key for a third-party service, a document stored for a user, a value in a cookie the client mustn't read. Always use authenticated encryption, which detects tampering. Unauthenticated modes like AES-CBC on their own let attackers flip bits in the ciphertext and sometimes recover the plaintext (padding-oracle attacks).

Sodium: the easy, safe choice

The sodium extension (libsodium, bundled with PHP since 7.2 but optional in some builds) offers high-level functions that are hard to misuse. For encrypting with a secret key, sodium_crypto_secretbox() does everything right:

PHP
<?php
// The sodium extension isn't enabled on our online runner, so this example is read-only.

$key = sodium_crypto_secretbox_keygen();                         // 32 random bytes; store it safely
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);       // 24 bytes, new for every message

$ciphertext = sodium_crypto_secretbox('API key: sk_live_123', $nonce, $key);
$stored = base64_encode($nonce . $ciphertext);                   // keep the nonce with the ciphertext

// Later
$decoded = base64_decode($stored);
$nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plain = sodium_crypto_secretbox_open(substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES), $nonce, $key);

if ($plain === false) {
    throw new RuntimeException('Message was tampered with or the key is wrong.');
}

sodium_memzero($key);   // wipe the key from memory when done

Sodium also covers public-key encryption (sodium_crypto_box), signatures (sodium_crypto_sign), password hashing with Argon2 and key derivation. Check whether your PHP has it with extension_loaded('sodium'); on most Linux distributions it's a separate package such as php8.5-sodium or part of the default build.

OpenSSL with AES-256-GCM

The OpenSSL extension is available almost everywhere, including our editor. Its API is lower-level, so you must choose the cipher and handle the IV and tag yourself. Use AES-256-GCM, an authenticated mode: encryption produces a tag, and decryption fails if the ciphertext, IV or tag was changed.

PHP Authenticated encryption with AES-256-GCM

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The same plaintext encrypts to different output each time because each message gets a fresh random IV, so an observer can't tell that two records hold the same value. Changing a single bit or using the wrong key makes openssl_decrypt() return false, which our decrypt() turns into null. The tag check is what makes GCM authenticated.

Never reuse an IV (nonce) with the same key in GCM. Two messages encrypted with the same key and IV leak information about both plaintexts and let attackers forge messages. Always generate a fresh random IV per message, as the example does. Also avoid ECB mode completely (aes-256-ecb): it encrypts identical blocks identically, so patterns in the data remain visible.

Where do keys live?

Encryption moves the problem from protecting data to protecting the key. Keep keys out of your code and out of the database that holds the encrypted data: load them from environment variables or a secrets manager, as described in Deploying PHP Applications. Store keys as base64 or hex text and decode them when loading. Plan for key rotation: prefix each ciphertext with a key ID so old data can still be decrypted after you introduce a new key.

What not to build yourself

Cryptography fails in ways that tests don't catch. Code that encrypts and decrypts correctly can still be completely insecure. A few firm rules:

  • Don't invent algorithms or protocols. No XOR "encryption", no custom character shuffling, no base64_encode() as "encryption" (it's just an encoding anyone can reverse).
  • Don't hash passwords with hash(). Use password_hash().
  • Don't use == or === to compare secrets. Use hash_equals().
  • Don't use rand(), mt_rand(), uniqid() or timestamps for tokens. Use random_bytes() or Randomizer.
  • Don't encrypt without authentication, and don't build "encrypt-then-MAC" by hand when sodium or AES-GCM does it for you.
  • Don't build your own JWT, OAuth or session system. Use maintained libraries (such as firebase/php-jwt or lcobucci/jwt) or your framework's implementation, and keep them updated.
  • Do use HTTPS everywhere. It encrypts all traffic between browsers and your server, and nothing in PHP replaces it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A payment provider sends webhooks and you must be sure they really came from the provider. Which tool fits?

    Anyone can compute a plain hash. Only someone who knows the shared key can produce a valid HMAC.
  2. 2. Which function is NOT suitable for generating a password-reset token?

    mt_rand() uses the Mersenne Twister, whose output can be predicted after observing some values or guessing the seed.
  3. 3. What does openssl_decrypt() with AES-256-GCM return if one bit of the ciphertext was changed?

    GCM is authenticated encryption. Any change to the ciphertext, IV or tag makes decryption fail.
  4. 4. You encrypt the same text twice with the same key using random IVs. What do you observe?

    A fresh IV per message makes every ciphertext different, so equal values can't be spotted. Reusing an IV with GCM is dangerous.
  5. 5. Why is hash('sha256', $key . $message) a poor signature?

    With SHA-2, knowing the hash of key + message lets an attacker compute the hash of key + message + extra data without the key.

Summary

  • Hashing (hash(), hash_file()) fingerprints data; use SHA-2 or SHA-3 for security, xxHash for speed, never MD5/SHA-1 for anything security related.
  • HMAC (hash_hmac()) proves that data came unchanged from a key holder: webhooks, signed URLs, tamper-proof tokens. Compare with hash_equals(); never use hash($key . $message).
  • Secure randomness comes from random_bytes(), random_int() and Random\Randomizer (8.2) with its default secure engine. rand(), mt_rand(), uniqid() and timestamps are predictable. Seeded engines are for tests only.
  • Encryption must be authenticated: sodium_crypto_secretbox() is the simplest safe choice; with OpenSSL use AES-256-GCM, a fresh random IV per message, and check the tag.
  • Keep keys out of code and the database, derive separate keys with hash_hkdf(), and plan for rotation.
  • Don't invent cryptography. Use the built-in functions and maintained libraries, and HTTPS everywhere.

Next: Secure Coding Checklist