/** @var CryptoRegistry $registry */
$registry = \Civi::service('crypto.registry');
- $parts = explode($this->delim, $token);
- if ($parts[1] !== self::VERSION_1) {
- throw new CryptoException("Unrecognized encoding");
+ $parts = explode($this->delim, $token, 4);
+ if (count($parts) !== 4 || $parts[1] !== self::VERSION_1) {
+ throw new CryptoException("Cannot decrypt token. Invalid format.");
}
$keyId = $parts[2];
$cipherText = base64_decode($parts[3]);
namespace Civi\Crypto;
+use Civi\Crypto\Exception\CryptoException;
+
/**
* Test major use-cases of the 'crypto.token' service.
*/
$this->assertTrue($token->isPlainText("\n"));
}
+ public function testDecryptInvalid() {
+ $cryptoToken = \Civi::service('crypto.token');
+ try {
+ $cryptoToken->decrypt(chr(2) . 'CTK0' . chr(2));
+ $this->fail("Expected CryptoException");
+ }
+ catch (CryptoException $e) {
+ $this->assertRegExp(';Cannot decrypt token. Invalid format.;', $e->getMessage());
+ }
+
+ $goodExample = $cryptoToken->encrypt('mess with me', 'UNIT-TEST');
+ $this->assertEquals('mess with me', $cryptoToken->decrypt($goodExample));
+
+ try {
+ $badExample = preg_replace(';CTK0;', 'ctk9', $goodExample);
+ $cryptoToken->decrypt($badExample);
+ $this->fail("Expected CryptoException");
+ }
+ catch (CryptoException $e) {
+ $this->assertRegExp(';Cannot decrypt token. Invalid format.;', $e->getMessage());
+ }
+ }
+
public function getExampleTokens() {
return [
// [ 'Plain text', 'Encryption Key ID', 'expectTokenRegex', 'expectTokenLen', 'expectPlain' ]