Skip to content

Instantly share code, notes, and snippets.

@beisong7
Last active February 5, 2021 21:46
Show Gist options
  • Save beisong7/4a235666e2ce7a8ea120e93c4a4638fd to your computer and use it in GitHub Desktop.
Save beisong7/4a235666e2ce7a8ea120e93c4a4638fd to your computer and use it in GitHub Desktop.
Simple Encrypt and Decrypt
<?php
public function decrypt($payload, $password, $iv = null, $method=null){
if(empty($method)){
$method = "AES-128-CBC";
}
if(empty($iv)){
$iv = "";
}
$decryption = openssl_decrypt($payload, $method, $password, OPENSSL_ZERO_PADDING, $iv);
$decryption = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $decryption);
return trim($decryption);
}
function my_encrypt($data, $password, $method) {
// Remove the base64 encoding from our key
$encryption_key = base64_decode($password);
// Generate an initialization vector
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
// Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
$encrypted = openssl_encrypt($data, $method, $encryption_key, 0, $iv);
echo "<br>";
// The $iv is just as important as the key for decrypting, so save it with our encrypted data using a unique separator (::)
return [$encrypted, $iv];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment