security

OpenSSL And Sodium Overview

PHP exposes cryptographic tools through OpenSSL and Sodium. Application code should use high-level, reviewed designs because choosing algorithms, nonces, keys, and encodings incorrectly can make apparently encrypted data unsafe.

Core Controls

  • Prefer Sodium high-level APIs for application-level authenticated encryption when available.
  • Use authenticated encryption so tampering is detected.
  • Keep keys outside source control and rotate them deliberately.
  • Use OpenSSL for standards and integrations that require it, such as certificate handling.
  • Do not invent encryption formats or reuse nonces incorrectly.

Authenticated Encryption With Sodium

Authenticated encryption protects confidentiality and detects tampering.

PHP example
<?php

declare(strict_types=1);

$key = sodium_crypto_secretbox_keygen();
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox('private note', $nonce, $key);
$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);

echo $plaintext . PHP_EOL;

// Prints:
// private note

The nonce is not secret, but it must not be reused with the same key. Store a versioned payload that includes the nonce and ciphertext. Keep the key outside source control.

Plan Key Rotation

Encryption creates an operational dependency on keys. Decide where keys live, who may access them, how backups are protected, and how old data is decrypted while a new key is rolled out.

A simple key-version field lets the application choose the correct decryption key and gradually re-encrypt old values.

Use The Right Primitive

Password hashing, message authentication, encryption, and TLS solve different problems. Use password_hash() for passwords. Use HTTPS for data in transit. Use a high-level authenticated-encryption API only when stored data genuinely needs reversible protection.

In Application Work

Password hashing is not encryption, and encryption is not a substitute for TLS. Ask whether the application needs to store the sensitive value at all before encrypting it.

What To Check

Before moving on, make sure you can explain authenticated encryption, nonce uniqueness, key storage and rotation, and why encryption should not replace password hashing or TLS.

Practice

Practice: Review An Encrypted Field Design

Requirements

  • State why the value must be stored.
  • Choose an authenticated encryption API.
  • Describe key storage and rotation.
  • Plan failure handling when decryption fails.
Show solution

Review Points

  • Prefer Sodium high-level APIs for application-level authenticated encryption when available.
  • Use authenticated encryption so tampering is detected.
  • Keep keys outside source control and rotate them deliberately.
  • Use OpenSSL for standards and integrations that require it, such as certificate handling.
  • Do not invent encryption formats or reuse nonces incorrectly.