Skip to content

Instantly share code, notes, and snippets.

@gmambro
Created March 9, 2017 16:47
Show Gist options
  • Save gmambro/3937a07216286de290f74af17981a209 to your computer and use it in GitHub Desktop.
Save gmambro/3937a07216286de290f74af17981a209 to your computer and use it in GitHub Desktop.
Simple PHP encryption
class Encryption
{
const CIPHER = 'AES-128-CBC';
/* Cryptographic key of length 16, 24 or 32. NOT a password! */
private $key;
private $iv_size;
public function __construct($key) {
$this->key = $key;
$this->iv_size = openssl_cipher_iv_length($this::CIPHER);
}
public function encrypt($plaintext) {
$iv = openssl_random_pseudo_bytes($this->iv_size);
$ciphertext = openssl_encrypt($plaintext, $this::CIPHER, $this->key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv.$ciphertext);
}
public function decrypt($ciphertext) {
$ciphertext = base64_decode($ciphertext);
if (strlen($ciphertext) < $this->iv_size) {
throw new Exception('Missing initialization vector');
}
$iv = substr($ciphertext, 0, $this->iv_size);
$ciphertext = substr($ciphertext, $this->iv_size);
$plaintext = openssl_decrypt($ciphertext, $this::CIPHER, $this->key, OPENSSL_RAW_DATA, $iv);
return rtrim($plaintext, "\0");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment