Skip to content

PHP Password encryption example

<?php

//$key is provided as hex string
function encrypt($plainText, $key)
{
    //key need to be converted to bytes array
    $key = hex2bin($key);
    //algorithm that we use here is connected with key length
    //in example we use 256bit key for different length please use proper cipher for example aes-256-gcm
    //more information about possible values https://www.php.net/manual/en/function.openssl-get-cipher-methods.php
    $cipher = "aes-256-gcm";
    //discover length of Initialization Vector that should be use with selected cipher method
    $ivlen = openssl_cipher_iv_length($cipher);
    //random iv
    $iv = openssl_random_pseudo_bytes($ivlen);
    //encryption
    //we instruct openssl to use NO_PADDING
    $ciphertext_raw = openssl_encrypt($plainText, $cipher, $key, OPENSSL_ZERO_PADDING | OPENSSL_RAW_DATA, $iv, $tag);
    //output is base64 encoded iv and cipher with tag
    return array(base64_encode($iv), base64_encode($ciphertext_raw . $tag));
}

//$key is provided as hex string
function decrypt($cipherBase64Encoded, $ivBase64Encoded, $key)
{
    //key need to be converted to bytes array
    $key = hex2bin($key);
    //algorithm that we use here is connected with key length
    //in example we use 256bit key for different length please use proper cipher for example aes-256-gcm
    //more information about possible values https://www.php.net/manual/en/function.openssl-get-cipher-methods.php
    $cipher = "aes-256-gcm";
    //decode iv from base64
    $iv = base64_decode($ivBase64Encoded);
    //encryption
    $cipherText = base64_decode($cipherBase64Encoded);
    //cipher without tag
    $tagLength = 16;
    $cipherWithoutTag = substr($cipherText, 0, strlen($cipherText) - $tagLength);
    //extracting tag from cipher
    $tag = substr($cipherText, strlen($cipherText) - $tagLength);
    //we instruct openssl to use NO_PADDING
    $plainText = openssl_decrypt($cipherWithoutTag, $cipher, $key, OPENSSL_ZERO_PADDING | OPENSSL_RAW_DATA, $iv, $tag);
    return $plainText;
}

//Text that should be encrypted
$plainText = "Password!1";
//encryption key 256bit
$hexKey = "C45B3B4E5CF954C50A654CA66190188E65305C514AF00934BCFDD965412338B4";

//Encryption
$encrypted = encrypt($plainText, $hexKey);

echo "\n===========\n";
echo "Plain Text: " . $plainText;
echo "\nKey: " . $hexKey;
echo "\nCipher Text: " . $encrypted[1];
echo "\nIV: " . $encrypted[0];
echo "\n===========\n";

//Decryption
$decryptedData = decrypt($encrypted[1], $encrypted[0], $hexKey);
echo "Decrypted Text: " . $decryptedData;
echo "\n===========\n";

?>