Skip to content

hook_civicrm_cryptoRotateKey

Summary

When a system administrator changes the cryptographic key used for data-storage, this event fires. Listen to this event to re-encrypt data with the new key.

Definition

hook_civicrm_cryptoRotateKey(string $tag, LoggerInterface $log)

Parameters

  • $tag (@param string) - Crypto keys are identified by tags, which determine their role/purpose within Civi. The old key and its replacement are identified by tag. Ex: CRED
  • $log (@param \Psr\Log\LoggerInterface) - An output channel where you may note progress (successful or erroneous) with rekeying.

Returns

  • null - the return value is ignored

Example

/**
 * Ensure that `some_table`.`secret_column` is encrypted with the `CRED` key.
 * Use the method `CryptoToken::rekey(...)` to re-encrypt specific values.
 */
function example_civicrm_cryptoRotateKey($tag, $log) {
  if ($tag !== 'CRED') return;

  $cryptoToken = Civi::service('crypto.token');

  $rows = sql('SELECT id, secret_column FROM some_table');
  foreach ($rows as $row) {
    $new = $cryptoToken->rekey($row['secret_column'], 'CRED');
    if ($new !== NULL) {
      sql('UPDATE some_table SET secret_column = %1 WHERE id = %2', $new, $row['id']);
      $log->info("Updated secret_column for #{id}", ['id' => $row['id']]);
    }
  }
}