Home > Backend Development > PHP Tutorial > How to Securely Encrypt and Decrypt PHP Strings Using Libsodium or defuse/php-encryption?

How to Securely Encrypt and Decrypt PHP Strings Using Libsodium or defuse/php-encryption?

Mary-Kate Olsen
Release: 2024-12-18 00:26:10
Original
123 people have browsed it

How to Securely Encrypt and Decrypt PHP Strings Using Libsodium or defuse/php-encryption?

Encrypting and Decrypting PHP Strings

Question:
How can we encrypt and decrypt a PHP string, requiring both an original string and a salt or key for both processes?

Answer:
It's crucial to understand the difference between encryption and authentication before proceeding. For robust security, we recommend encrypted authentication, which entails encrypting and then authenticating.

Avoid creating your own cryptography; instead, utilize a dependable library developed by cryptography specialists. We strongly advise using libsodium or defuse/php-encryption due to their ease of use and built-in authenticated encryption.

Encryption Steps:

  1. Employ AES in CTR mode for encryption.
  2. Authenticate the ciphertext using HMAC-SHA-256 (or Poly1305).

Decryption Steps:

  1. Recalculate the MAC of the ciphertext and compare it with the original MAC. Abort if there's a mismatch.
  2. Proceed with decryption.

Design Considerations:

  1. Avoid compressing ciphertext.
  2. Employ mb_strlen() and mb_substr() with the '8bit' character set mode.
  3. Utilize a CSPRNG to generate IVs. Avoid MCRYPT_RAND.
  4. Always encrypt before authenticating (unless using AEAD).
  5. Be mindful of cache timing vulnerabilities.

When Not to Use Encryption:

  • Password storage (use password-hashing algorithms like Argon2 instead)
  • URL parameter encryption (inappropriate tool)

Libsodium PHP Example:

function safeEncrypt(string $message, string $key): string
{
    if (mb_strlen($key, '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
        throw new RangeException('Key is not the correct size (must be 32 bytes).');
    }
    $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $cipher = base64_encode(
        $nonce.
        sodium_crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
    return $cipher;
}
Copy after login

Libsodium Decryption:

function safeDecrypt(string $encrypted, string $key): string
{
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
    $plain = sodium_crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
    return $plain;
}
Copy after login

defuse/php-encryption Example:

use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;

$message = 'We are all living in a yellow submarine';
$key = Key::createNewRandomKey();
$ciphertext = Crypto::encrypt($message, $key);
$plaintext = Crypto::decrypt($ciphertext, $key);
Copy after login

The above is the detailed content of How to Securely Encrypt and Decrypt PHP Strings Using Libsodium or defuse/php-encryption?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template