function encryption_requirements in Encryption 8
Same name and namespace in other branches
- 2.x encryption.install \encryption_requirements()
Implements hook_requirements().
- Checks the encryption key is a base 64 encoded 256 value.
- Tests decryption against a known value.
File
- ./
encryption.install, line 11
Code
function encryption_requirements($phase) {
$requirements = [];
if ($phase == 'runtime') {
/** @var \Drupal\encryption\EncryptionServiceInterface $encryption */
$encryption = Drupal::service('encryption');
// Check for the encryption_key entry in settings.
$encryption_key_raw = Settings::get('encryption_key', FALSE);
$key = base64_decode($encryption_key_raw);
$key_length = strlen($key);
$requirements['encryption'] = [
'title' => t('Encryption'),
];
if (empty($encryption_key_raw) || $key_length !== 32) {
$requirements['encryption'] += [
'severity' => REQUIREMENT_ERROR,
'description' => t('The encryption key must be a base 64 encoded 256 bit (32 byte) value.'),
'value' => $encryption_key_raw === FALSE ? t('The encryption key was not found.') : t('An encryption key of :length bits was found but a 256 bit key was expected.', [
':length' => $key_length * 8,
]),
];
}
else {
$requirements['encryption'] += [
'severity' => REQUIREMENT_OK,
'value' => t('The encryption key is OK.'),
];
}
// Use the state service to get an encrypted version of a test string.
$state = Drupal::state();
// Get the last stored encrypted value.
$result = $state
->get('encryption.test_value', FALSE);
// Text used for testing decryption.
$test_text = 'simple test value';
$reset = isset($_GET['encryption_reset_test_string']) && $_GET['encryption_reset_test_string'] === '1';
if ($result === FALSE || $reset) {
// Save an encrypted representation of the test string.
$state
->set('encryption.test_value', $encryption
->encrypt($test_text));
// Let the user know that the test value has been reset.
if ($reset) {
$requirements['encryption']['severity'] = REQUIREMENT_WARNING;
$requirements['encryption']['value'] = t('The encryption test value has been reset <a href="javascript:history.back()">(go back)</a>.');
}
}
else {
// Decrypt the result from the state service.
$decrypted_result = $encryption
->decrypt($result);
// Add the warning if everything else is OK.
if ($test_text != $decrypted_result && $requirements['encryption']['severity'] == REQUIREMENT_OK) {
$requirements['encryption']['severity'] = REQUIREMENT_WARNING;
$requirements['encryption']['value'] = t('Unable to properly decrypt the test value. Possible due to a change of the encryption key. <a href="?encryption_reset_test_string=1">Reset</a>');
$requirements['encryption']['description'] = t('Attempted to decrypt a known encrypted value. The test value is encrypted when the encryption module is installed.');
}
}
}
return $requirements;
}