Skip to content

Instantly share code, notes, and snippets.

@robertogallea
Created May 8, 2020 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertogallea/ffe9035a9a05efc294dca2ccfbeb1d71 to your computer and use it in GitHub Desktop.
Save robertogallea/ffe9035a9a05efc294dca2ccfbeb1d71 to your computer and use it in GitHub Desktop.
public function encrypt($value, $serialize = true)
{
$iv = random_bytes(openssl_cipher_iv_length($this->cipher));
$value = \openssl_encrypt(
$serialize ? serialize($value) : $value,
$this->cipher, $this->key, 0, $iv
);
if ($value === false) {
throw new EncryptException('Could not encrypt the data.');
}
$mac = $this->hash($iv = base64_encode($iv), $value);
$json = json_encode(compact('iv', 'value', 'mac'), JSON_UNESCAPED_SLASHES);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new EncryptException('Could not encrypt the data.');
}
return base64_encode($json);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment