Home > Backend Development > PHP Tutorial > How Can I Encrypt and Decrypt Strings Securely in PHP?

How Can I Encrypt and Decrypt Strings Securely in PHP?

Mary-Kate Olsen
Release: 2024-12-24 07:29:32
Original
836 people have browsed it

How Can I Encrypt and Decrypt Strings Securely in PHP?

How to Encrypt and Decrypt a PHP String with Key

Encrypting and decrypting strings in PHP involves utilizing cryptographic techniques to protect sensitive information.

Encryption

To encrypt a string using a secret key:

  1. Use AES in CTR mode: Encrypt the string using the Advanced Encryption Standard (AES) in Counter (CTR) mode.
  2. Authenticate the ciphertext: Calculate a Hash-based Message Authentication Code (HMAC) over the IV and ciphertext using HMAC-SHA-256 or Poly1305 (for stream ciphers).

Decryption

To decrypt an encrypted string using the same key:

  1. Check the MAC: Recalculate the MAC and compare it to the saved one.
  2. Decrypt the message: Decrypt the ciphertext using AES in CTR mode.

Other Considerations

  • Avoid compressing data before encryption.
  • Use mb_strlen() and mb_substr() with the '8bit' character set to prevent issues.
  • Generate IVs using a CSPRNG and avoid MCRYPT_RAND.
  • Always encrypt then MAC to ensure both confidentiality and authenticity.

Libsodium for PHP

If using PHP 7.2 or higher, consider using the libsodium library:

use ParagonIE\Halite\Symmetric\Crypto as SymmetricCrypto;

$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$ciphertext = SymmetricCrypto::encrypt($message, $key);
$plaintext = SymmetricCrypto::decrypt($ciphertext, $key);
Copy after login

defuse/php-encryption

As an alternative to libsodium:

use Defuse\Crypto\Crypto;

$key = Key::createNewRandomKey();
$ciphertext = Crypto::encrypt($message, $key);
$plaintext = Crypto::decrypt($ciphertext, $key);
Copy after login

Password Considerations

  • For passwords: Hash them using Argon2, scrypt, bcrypt, or PBKDF2-SHA256 with high iterations.
  • For authentication: Use HMAC-based algorithms like HKDF2 or hash_hmac() instead of encryption.
  • For URL parameters: Use an appropriate framework or library designed for URL parameter validation and tampering protection.

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