/** * 1. VerifyHMAC-then-Decrypt the ciphertext to get the hash * 2. Verify that the password matches the hash * * @param string $password * @param string $ciphertext * @param string $aesKey - must be exactly 16 bytes * @return boolean */ public static function decryptAndVerifyLegacy($password, $ciphertext, $aesKey) { if (self::safeStrlen($aesKey) !== 16) { throw new \Exception("Encryption keys must be 16 bytes long"); } $hash = Crypto::legacyDecrypt($ciphertext, $aesKey); return \password_verify(\base64_encode(\hash('sha256', $password, true)), $hash); }
/** * Decrypts data * * @param string $data The data to encrypt * * @return string The encrypted data * * @throws \CodeCollab\Encryption\CryptoException When the message could not be decrypted * @throws \CodeCollab\Encryption\FraudException When the message is potentially tampered with */ public function decrypt(string $data) : string { try { return Crypto::legacyDecrypt($data, $this->key); } catch (WrongKeyOrModifiedCiphertextException $e) { throw new FraudException($e->getMessage(), $e->getCode(), $e); } catch (EnvironmentIsBrokenException $e) { throw new CryptoException($e->getMessage(), $e->getCode(), $e); } }
/** * For migrating from an older version of the library * * @param string $password * @param string $ciphertext * @param string $oldKey * @param Key $newKey * @return string * @throws \Exception */ public static function upgradeFromVersion1(string $password, string $ciphertext, string $oldKey, Key $newKey) : string { if (!self::decryptAndVerifyLegacy($password, $ciphertext, $oldKey)) { throw new \Exception('The correct password is necessary for legacy migration.'); } $plaintext = Crypto::legacyDecrypt($ciphertext, $oldKey); return self::hashAndEncrypt($plaintext, $newKey); }
/** * @expectedException \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException */ public function testDecryptLegacyCiphertextWrongKey() { $cipher = Encoding::hexToBin('cfdad83ebd506d2c9ada8d48030d0bca' . '2ff94760e6d39c186adb1290d6c47e35' . '821e262673c5631c42ebbaf70774d6ef' . '29aa5eee0e412d646ae380e08189c85d' . '024b5e2009106870f1db25d8b85fd01f'); $plain = Crypto::legacyDecrypt($cipher, "\t\n\v\f\r"); }