Skip to content

Commit

Permalink
Merge pull request #21 from IlicMiljan/fix-parsing-tagged-encrypted-data
Browse files Browse the repository at this point in the history
Fix Parsing Tagged Encrypted Data
  • Loading branch information
IlicMiljan committed Mar 16, 2024
2 parents b80975b + 658e0b5 commit ab7b561
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/Cipher/TagAwareCipher.php
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 ab7b561

Please sign in to comment.