Skip to content

Commit

Permalink
Replace Regex Tag Detection With substr() Logic
Browse files Browse the repository at this point in the history
  • Loading branch information
IlicMiljan committed Mar 16, 2024
1 parent b80975b commit 658e0b5
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/Cipher/TagAwareCipher.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@

class TagAwareCipher implements Cipher
{
private const START_TAG = '<ENC>';
private const END_TAG = '</ENC>';

private Encoder $encoder;

public function __construct(
Expand All @@ -25,7 +28,7 @@ public function encrypt(#[SensitiveParameter] string $string): string
{
$encryptedString = $this->cipher->encrypt($string);

return $this->encoder->encode('<ENC>' . $encryptedString . '</ENC>');
return $this->encoder->encode(self::START_TAG . $encryptedString . self::END_TAG);
}

public function decrypt(#[SensitiveParameter] string $string): string
Expand All @@ -36,13 +39,20 @@ public function decrypt(#[SensitiveParameter] string $string): string
return $string;
}

preg_match('/^<ENC>(.*)<\/ENC>$/', $data, $matches);

return $this->cipher->decrypt($matches[1]);
return $this->cipher->decrypt($this->extractTaggedValue($data));
}

private function shouldDecrypt(string $string): bool
{
return preg_match('/^<ENC>(.*)<\/ENC>$/', $string) === 1;
return str_contains($string, self::START_TAG) && str_contains($string, self::END_TAG);
}

private function extractTaggedValue(string $string): string
{
$startPos = strpos($string, self::START_TAG);
$endPos = strpos($string, self::END_TAG);

$startPos += strlen(self::START_TAG);
return substr($string, $startPos, $endPos - $startPos);
}
}

0 comments on commit 658e0b5

Please sign in to comment.