*/
protected $delim;
+ /**
+ * @var \Civi\Crypto\CryptoRegistry|null
+ */
+ private $registry;
+
/**
* CryptoToken constructor.
+ *
+ * @param CryptoRegistry $registry
*/
- public function __construct() {
+ public function __construct($registry = NULL) {
$this->delim = chr(2);
+ $this->registry = $registry;
}
/**
* @return bool
*/
public function isPlainText($plainText) {
- return is_string($plainText) && ($plainText === '' || $plainText{0} !== $this->delim);
+ return is_string($plainText) && ($plainText === '' || $plainText[0] !== $this->delim);
}
/**
*/
public function encrypt($plainText, $keyIdOrTag) {
/** @var CryptoRegistry $registry */
- $registry = \Civi::service('crypto.registry');
+ $registry = $this->getRegistry();
$key = $registry->findKey($keyIdOrTag);
if ($key['suite'] === 'plain') {
}
/** @var CryptoRegistry $registry */
- $registry = \Civi::service('crypto.registry');
+ $registry = $this->getRegistry();
$tokenData = $this->parse($token);
return $plainText;
}
+ /**
+ * Re-encrypt an existing token with a newer version of the key.
+ *
+ * @param string $oldToken
+ * @param string $keyTag
+ * Ex: 'CRED'
+ *
+ * @return string|null
+ * A re-encrypted version of $oldToken, or NULL if there should be no change.
+ * @throws \Civi\Crypto\Exception\CryptoException
+ */
+ public function rekey($oldToken, $keyTag) {
+ /** @var \Civi\Crypto\CryptoRegistry $registry */
+ $registry = $this->getRegistry();
+
+ $sourceKeys = $registry->findKeysByTag($keyTag);
+ $targetKey = array_shift($sourceKeys);
+
+ if ($this->isPlainText($oldToken)) {
+ if ($targetKey['suite'] === 'plain') {
+ return NULL;
+ }
+ }
+ else {
+ $tokenData = $this->parse($oldToken);
+ if ($tokenData['k'] === $targetKey['id'] || !isset($sourceKeys[$tokenData['k']])) {
+ return NULL;
+ }
+ }
+
+ $decrypted = $this->decrypt($oldToken);
+ return $this->encrypt($decrypted, $targetKey['id']);
+ }
+
/**
* Parse the content of a token (without decrypting it).
*
return $tokenData;
}
+ /**
+ * @return CryptoRegistry
+ */
+ protected function getRegistry(): CryptoRegistry {
+ if ($this->registry === NULL) {
+ $this->registry = \Civi::service('crypto.registry');
+ }
+ return $this->registry;
+ }
+
}