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:
Decryption
To decrypt an encrypted string using the same key:
Other Considerations
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);
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);
Password Considerations
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!