Skip to content

Instantly share code, notes, and snippets.

@abidkhan484
Created June 13, 2024 04:00
Show Gist options
  • Save abidkhan484/7e759ca493ac73ee3f956cf5f9d9b586 to your computer and use it in GitHub Desktop.
Save abidkhan484/7e759ca493ac73ee3f956cf5f9d9b586 to your computer and use it in GitHub Desktop.
OpenSSL encryption example with AES-256-CBC
<?php
$privateKey = 'someprivatekey';
$secretInfo = 'secretInfo';
$method = 'aes-256-cbc';
$ivLength = openssl_cipher_iv_length($method);
$iv = random_bytes($ivLength);
$encryptedData = openssl_encrypt($secretInfo, $method, $privateKey, OPENSSL_RAW_DATA, $iv);
$token = base64_encode($iv . $encryptedData);
echo "Encrypted token: " . $token . "\n";
$data = base64_decode($token);
$ivLength = openssl_cipher_iv_length($method);
$iv = substr($data, 0, $ivLength);
$encryptedData = substr($data, $ivLength);
$decrypted = openssl_decrypt($encryptedData, $method, $privateKey, OPENSSL_RAW_DATA, $iv);
echo $decrypted;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment