This article will explain how to encrypt or hash contact fields using Twig. You can use this to securely add links containing personal data to an email. For example, to send your customers a personalized survey.
Encryption
The Twig filter encrypt accepts two parameters.
- The first parameter is required. This is the base64 encoded Key to be used in the encryption. The Key should be generated in a cryptographically secure way, like with openssl_random_pseudo_bytes.
- The second parameter is optional. This is the cipher method to be used in the encryption. The default value is "aes-256-cbc". This parameter is checked against the list of ciphers that the OpenSSL library used on the web servers provides. This might change in future PHP versions.
The response of the function is a base64 encoded string that is built up as follows:
iv: the random-generated initialization vector with the length needed by the cipher - tag: only used with some ciphers, with a length of 16 - encrypted data.
See the Twig code below for examples of encryption with one parameter or with two parameters.
{{ contact.email|encrypt('base64_encoded_key')|url_encode }}
{{ contact.email|encrypt('base64_encoded_key', 'aes-256-cbc')|url_encode }}
Decryption
In general, you need to do the following to decrypt the contact field:
Base64 decode the encrypted input. This results in a concatenated string with the IV, optional tag and encrypted data. The length of the IV is dependent on the cipher method used. For AES, it’s 16 bytes. In case the cipher method generates a tag on encryption, that tag is the following 16 bytes of the base64 decoded string. The rest of the base64 decoded string is the encrypted data. With the IV, optional tag and key, you decrypt the encrypted data.
Here’s a PHP code example to decrypt the data. By default, we use the AES-256-CBC cipher method.
$base64Decoded = base64_decode($encrypted);
$ivLength = openssl_cipher_iv_length($cipher);
$iv = substr($base64Decoded, 0, $ivLength);
if (preg_match('/-(ccm|gcm|ocb)/', $cipher)) {
$tag = substr($base64Decoded, $ivLength, 16);
$encryptedData = substr($base64Decoded, $ivLength + 16);
} else {
$tag = null;
$encryptedData = substr($base64Decoded, $ivLength);
}
$decrypted = openssl_decrypt($encryptedData, $cipher, base64_decode($key), OPENSSL_RAW_DATA, $iv, $tag);
Hashing
See the supported hashing algorithms here: https://www.php.net/manual/en/function.hash-algos.php. See the Twig code below for an example.
{{ variable|hash("algorithm") }} Example: {% set string = "string" %} {{ string|hash("sha256") }} Shows: 473287f8298dba7163a897908958f7c0eae733e25d2e027992ea2edc9bed2fa8