Skip to content

Instantly share code, notes, and snippets.

@satyendrakumarsingh
Created April 24, 2024 01:48
Show Gist options
  • Save satyendrakumarsingh/aea6d7ceab7de9334a3f065e837d9a37 to your computer and use it in GitHub Desktop.
Save satyendrakumarsingh/aea6d7ceab7de9334a3f065e837d9a37 to your computer and use it in GitHub Desktop.
php-aes-gcm
<?php
class AESGCMUtil {
const AES_KEY_SIZE = 256; // Key size for AES
const GCM_IV_LENGTH = 12; // IV length for GCM
const GCM_TAG_LENGTH = 16; // Authentication tag length for GCM
/**
* Prevent instantiation of the class.
*/
private function __construct()
{
}
/**
* Generate a random nonce (IV).
*
* @return string Hexadecimal representation of the IV
*/
public static function getRandomNonce()
{
$ivBytes = random_bytes(self::GCM_IV_LENGTH);
return bin2hex($ivBytes);
}
/**
* Generate a secret encryption key.
*
* @return string Hexadecimal representation of the AES key
*/
public static function getSecretEncryptionKey()
{
$key = openssl_random_pseudo_bytes(self::AES_KEY_SIZE / 8);
return bin2hex($key);
}
/**
* Encrypt a plaintext string.
*
* @param string $plainText The plaintext message to encrypt
* @param string $secKey Hexadecimal string of the secret key
* @param string $ivData Hexadecimal string of the IV
* @return string Hexadecimal encrypted text
*/
public static function encrypt($plainText, $secKey, $ivData)
{
$key = hex2bin($secKey);
$iv = hex2bin($ivData);
$cipherText = openssl_encrypt($plainText, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, '', self::GCM_TAG_LENGTH);
$cipherHex = bin2hex($cipherText . $tag); // Concatenate cipher text and tag for storage
return $cipherHex;
}
/**
* Decrypt an encrypted string.
*
* @param string $encHexString Hexadecimal string of the encrypted text and tag
* @param string $secKey Hexadecimal string of the secret key
* @param string $ivData Hexadecimal string of the IV
* @return string Decrypted text
*/
public static function decrypt($encHexString, $secKey, $ivData)
{
$key = hex2bin($secKey);
$iv = hex2bin($ivData);
$encTextWithTag = hex2bin($encHexString);
$cipherText = substr($encTextWithTag, 0, -self::GCM_TAG_LENGTH);
$tag = substr($encTextWithTag, -self::GCM_TAG_LENGTH);
$decryptedText = openssl_decrypt($cipherText, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
return $decryptedText;
}
}
// Example Usage:
$nonce = AESGCMUtil::getRandomNonce();
$key = AESGCMUtil::getSecretEncryptionKey();
echo "Nounce/IV: " . $nonce . "\n";
echo "AES Key: " . $key . "\n";
$encrypted = AESGCMUtil::encrypt("satyendra", $key, $nonce);
$decrypted = AESGCMUtil::decrypt($encrypted, $key, $nonce);
echo "Encrypted: " . strtoupper($encrypted) ."\n";
echo "Decrypted: " . $decrypted . "\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment