Security Utility
The security libraryhandles basic security measures such as providing methods forhashing and encrypting data.
Encrypting and Decrypting Data
Encrypt $text
using AES-256. The $key
should be a value with alots of variance in the data much like a good password. The returned resultwill be the encrypted value with an HMAC checksum.
The openssl extension is required for encrypting/decrypting.
An example use would be:
- // Assuming key is stored somewhere it can be re-used for
- // decryption later.
- $key = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
- $result = Security::encrypt($value, $key);
If you do not supply an HMAC salt, the value of Security::getSalt()
will be used.Encrypted values can be decrypted usingCake\Utility\Security::decrypt()
.
This method should never be used to store passwords.
Decrypt a previously encrypted value. The $key
and $hmacSalt
parameters must match the values used to encrypt or decryption will fail. Anexample use would be:
- // Assuming the key is stored somewhere it can be re-used for
- // Decryption later.
- $key = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
- $cipher = $user->secrets;
- $result = Security::decrypt($cipher, $key);
If the value cannot be decrypted due to changes in the key or HMAC saltfalse
will be returned.
Hashing Data
Create a hash from string using given method. Fallback on nextavailable method. If $salt
is set to true
, the application’s saltvalue will be used:
- // Using the application's salt value
- $sha1 = Security::hash('CakePHP Framework', 'sha1', true);
- // Using a custom salt value
- $sha1 = Security::hash('CakePHP Framework', 'sha1', 'my-salt');
- // Using the default hash algorithm
- $hash = Security::hash('CakePHP Framework');
The hash()
method supports the following hashing strategies:
- md5
- sha1
- sha256
And any other hash algorithmn that PHP’s hash()
function supports.
Warning
You should not be using hash()
for passwords in new applications.Instead you should use the DefaultPasswordHasher
class which uses bcryptby default.
Getting Secure Random Data
Get $length
number of bytes from a secure random source. This function drawsdata from one of the following sources:
- PHP’s
random_bytes
function. openssl_random_pseudo_bytes
from the SSL extension.
If neither source is available a warning will be emitted and an unsafe valuewill be used for backwards compatibility reasons.
Get a random string $length
long from a secure random source. This methoddraws from the same random source as randomBytes()
and will encode the dataas a hexadecimal string.