Last active
April 10, 2024 13:58
-
-
Save daveh/4656141ee026c897c4dcc594fedf51fe to your computer and use it in GitHub Desktop.
Encrypt and Decrypt Data Securely in PHP: OpenSSL, Sodium & defuse/php-encryption (code to accompany https://youtu.be/VCdFFQvJl2k)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$cipher_algo = 'AES-256-CBC'; | |
$key = 'encryption key here'; | |
$iv_length = openssl_cipher_iv_length($cipher_algo); | |
$iv = openssl_random_pseudo_bytes($iv_length); | |
// $options = OPENSSL_RAW_DATA; | |
$options = 0; | |
$plaintext = readline('Enter some text: '); | |
$ciphertext = openssl_encrypt($plaintext, $cipher_algo, $key, $options, $iv); | |
echo "Original string: $plaintext\n"; | |
echo "Encrypted string: $ciphertext\n"; | |
$decrypted = openssl_decrypt($ciphertext, $cipher_algo, $key, $options, $iv); | |
echo "Decrypted string: $decrypted\n"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Defuse\Crypto\Key; | |
use Defuse\Crypto\Crypto; | |
require 'vendor/autoload.php'; | |
$key_ascii = 'encryption key here'; | |
$key = Key::loadFromAsciiSafeString($key_ascii); | |
$plaintext = readline('Enter some text: '); | |
$ciphertext = Crypto::encrypt($plaintext, $key); | |
echo "Original string: $plaintext\n"; | |
echo "Encrypted string: $ciphertext\n"; | |
$decrypted = Crypto::decrypt($ciphertext, $key); | |
echo "Decrypted string: $decrypted\n"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$key = 'encryption key here'; | |
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); | |
$plaintext = readline('Enter some text: '); | |
$ciphertext = sodium_crypto_secretbox($plaintext, $nonce, $key); | |
echo "Original string: $plaintext\n"; | |
echo "Encrypted string: $ciphertext\n"; | |
echo "Encrypted string hex: " . bin2hex($ciphertext) . "\n"; | |
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key); | |
echo "Decrypted string: $decrypted\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment