Hi,
I'm trying to migrate my APP from Yii2 (PHP 7.4) to Laravel 12 (PHP 8.4) and I also want to move from MySQL 5.7 to Postgres.
In the old app I used to encrypt PII data and saved it to the database like this:
$data = \Yii::$app->security->encryptByPassword(serialize($pii), env('PII_ENCRYPTION_PASSWORD'));
$this->data['pii'] = bin2hex($data);
$data is a json column in MySQL 5.7.
Now I want to decrypt the data, because I want to extract some of them for statistics.
In my Yii2 app I do it like this:
$pii = unserialize(Yii::$app->security->decryptByPassword(hex2bin($data), env('PII_ENCRYPTION_PASSWORD')));
In laravel I tried to copy all relavant code from \yii\base\Security::decryptByPassword and I ensured via debugging settings like $keySize. Because it didn't work I found that the output from hex2bin is different from one app to another.
Is that possible for different PHP versions? Do I have invisible charactores in my yii2 code?
My current code looks like this:
class Yii2Decryptor
{
protected string $cipher = 'AES-256-CBC';
protected string $kdfHash = 'sha256';
protected string $macHash = 'sha256';
protected int $derivationIterations = 100000;
protected string $authKeyInfo = 'AuthorizationKey';
protected int $keySize = 16;
protected int $blockSize = 16;
public function decrypt(string $hexData, string $password): ?string
{
$data = hex2bin($hexData);
$keySalt = $this->byteSubstr($data, 0, $this->keySize);
$key = hash_pbkdf2($this->kdfHash, $password, $keySalt, $this->derivationIterations, $this->keySize, true);
$authKey = hash_hkdf($this->kdfHash, $key, $this->keySize, $this->authKeyInfo, $keySalt);
dump($hexData, $data, $keySalt, $key, $authKey); // $data is already different. Next line $data is `false`
$data = $this->validateData($this->byteSubstr($data, $this->keySize), $authKey);
if ($data === false) {
return null;
}
$iv = $this->byteSubstr($data, 0, $this->blockSize);
$encrypted = $this->byteSubstr($data, $this->blockSize);
$decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
return $decrypted === false ? null : $decrypted;
}
private function byteSubstr(string $data, int $start, ?int $length = null): string
{
if ($length === null) {
$length = $this->byteLength($data);
}
return mb_substr($data, $start, $length, '8bit');
}
private function byteLength(string $data): int
{
return mb_strlen($data, '8bit');
}
protected function validateData(string $data, string $key): false|string
{
$test = hash_hmac($this->macHash, '', '');
$hasLength = $this->byteLength($test);
if ($this->byteLength($data) >= $hasLength) {
$hash = $this->byteSubstr($data, 0, $hasLength);
$pureData = $this->byteSubstr($data, $hasLength);
$calculatedHash = hash_hmac($this->macHash, $pureData, $key);
if (hash_equals($hash, $calculatedHash)) {
return $pureData;
}
}
return false;
}
}
The fact that already the output from hex2bin is different is driving me nuts...