Skip to content

Instantly share code, notes, and snippets.

@jcorry
Created July 29, 2015 17:49
Show Gist options
  • Save jcorry/109eba8df7931f37b9d0 to your computer and use it in GitHub Desktop.
Save jcorry/109eba8df7931f37b9d0 to your computer and use it in GitHub Desktop.
private function encrypt($message, $key, $encode = true) {
$method = 'aes-256-ctr';
$ivSize = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivSize);
$cipherText = openssl_encrypt(
$message,
$method,
$key,
OPENSSL_RAW_DATA,
$iv
);
if ($encode) {
return base64_encode($iv.$cipherText);
}
return $iv.$cipherText;
}
private function decrypt($message, $key, $encoded = true) {
$method = 'aes-256-ctr';
if($encoded) {
$message = base64_decode($message, true);
if($message === false) {
throw new Exception('Encryption fail at base64_decode');
}
}
$ivSize = openssl_cipher_iv_length($method);
$iv = mb_substr($message, 0, $ivSize, '8bit');
$cipherText = mb_substr($message, $ivSize, null, '8bit');
$plainText = openssl_decrypt(
$cipherText,
$method,
$key,
OPENSSL_RAW_DATA,
$iv
);
return $plainText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment