Skip to content

Instantly share code, notes, and snippets.

@Martyr2
Created September 23, 2017 17:23
Show Gist options
  • Save Martyr2/29943e56cd0e7823748960c20b15d2ab to your computer and use it in GitHub Desktop.
Save Martyr2/29943e56cd0e7823748960c20b15d2ab to your computer and use it in GitHub Desktop.
Simple encryption / decryption utility class which uses openssl. Be sure to supply a strong cryptographic key. Change method as you see fit.
<?php
/**
* Static class for simple encryption and decryption utilities.
*/
class Cryptor {
// This key is used if one is not supplied during encryption / decryption.
private const UNIQUE_KEY = '<some default key here>';
private const METHOD = 'AES-256-CTR';
public static function encrypt($text, $key = null) {
if (self::isSupported()) {
$ivlen = openssl_cipher_iv_length(self::METHOD);
$iv = openssl_random_pseudo_bytes($ivlen);
$keyVal = is_string($key) ? $key : self::UNIQUE_KEY;
$ciphertext_raw = openssl_encrypt($text, self::METHOD, $keyVal, $options = OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $keyVal, $as_binary = true);
return base64_encode($iv.$hmac.$ciphertext_raw);
} else {
throw new Exception("This environment doesn't support this kind of encryption.");
}
}
public static function decrypt($text, $key = null) {
if (self::isSupported()) {
$baseDecodedText = base64_decode($text);
$ivlen = openssl_cipher_iv_length(self::METHOD);
$iv = substr($baseDecodedText, 0, $ivlen);
$hmac = substr($baseDecodedText, $ivlen, $sha2len = 32);
$ciphertext_raw = substr($baseDecodedText, $ivlen+$sha2len);
$keyVal = is_string($key) ? $key : self::UNIQUE_KEY;
$original_plaintext = openssl_decrypt($ciphertext_raw, self::METHOD, $keyVal, $options = OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $keyVal, $as_binary = true);
if (hash_equals($hmac, $calcmac)) {
return $original_plaintext;
} else {
return false;
}
} else {
throw new Exception("This environment doesn't support this kind of decryption.");
}
}
public static function isSupported() {
return (extension_loaded('openssl') && function_exists('openssl_encrypt'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment