Skip to content

Instantly share code, notes, and snippets.

@delboy1978uk
Created December 13, 2019 14:23
Show Gist options
  • Save delboy1978uk/ebb438524972bb6b64596df7e9782f6e to your computer and use it in GitHub Desktop.
Save delboy1978uk/ebb438524972bb6b64596df7e9782f6e to your computer and use it in GitHub Desktop.
SSL encryption/decryption
class Ssl
{
private $cipher = "aes-128-gcm";
private $options = 0;
/**
* @param string $plaintext
* @return array
*/
public function encrypt($plaintext)
{
$key = \openssl_random_pseudo_bytes(16);
$ivlen = \openssl_cipher_iv_length($this->cipher);
$iv = \openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($plaintext, $this->cipher, $key, $this->options, $iv,$tag);
return array(
'key' => \bin2hex($key),
'iv' => \bin2hex($iv),
'tag' => \bin2hex($tag),
'ciphertext' => $ciphertext,
);
}
/**
* @param string $json
* @return false|string
*/
public function decrypt($json, $key)
{
$data = \json_decode($json);
$result = \openssl_decrypt($data->ciphertext, $this->cipher, \hex2bin($key), $this->options, \hex2bin($data->iv), \hex2bin($data->tag));
return \json_decode($result, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment