Home > Backend Development > PHP Tutorial > How to Securely Encrypt and Decrypt PHP Strings Using libsodium?

How to Securely Encrypt and Decrypt PHP Strings Using libsodium?

Patricia Arquette
Release: 2024-12-18 03:00:10
Original
921 people have browsed it

How to Securely Encrypt and Decrypt PHP Strings Using libsodium?

How to Encrypt and Decrypt a PHP String

When discussing encryption, it's important to distinguish between encryption and authentication. Typically, authenticated encryption, which combines encryption with message authentication code (MAC), is preferred. To ensure security, it's highly recommended to avoid implementing your own cryptography and instead rely on well-established libraries developed and reviewed by cryptographic experts.

Encryption Steps Using libsodium:

  1. Encrypt the message using AES in CTR mode or use GCM, which handles authentication implicitly.
  2. Authenticate the ciphertext using HMAC-SHA-256, ensuring the MAC covers both the IV and the ciphertext.

Decryption Steps Using libsodium:

  1. Verify the MAC of the ciphertext against the received MAC. Abort if the verification fails, indicating data corruption.
  2. Decrypt the message using the authenticated encryption method.

Additional Considerations:

  • Avoid compressing anything before encryption.
  • Use appropriate string manipulation functions that handle extended character sets.
  • Generate IVs securely using a cryptographically secure pseudorandom number generator (CSPRNG).
  • Always perform encryption before MAC to prevent vulnerabilities.
  • Be aware of potential information leakage issues with certain encoding methods.

Example Code with libsodium:

<?php
declare(strict_types=1);

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 * @throws RangeException
 */
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
        )
    );
    sodium_memzero($message);
    sodium_memzero($key);
    return $cipher;
}

/**
 * Decrypt a message
 * 
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 * @throws Exception
 */
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
    );
    if (!is_string($plain)) {
        throw new Exception('Invalid MAC');
    }
    sodium_memzero($ciphertext);
    sodium_memzero($key);
    return $plain;
}
?>
Copy after login

The above is the detailed content of How to Securely Encrypt and Decrypt PHP Strings Using libsodium?. 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