88
99class TagAwareCipher implements Cipher
1010{
11+ private const START_TAG = '<ENC> ' ;
12+ private const END_TAG = '</ENC> ' ;
13+
1114 private Encoder $ encoder ;
1215
1316 public function __construct (
@@ -25,7 +28,7 @@ public function encrypt(#[SensitiveParameter] string $string): string
2528 {
2629 $ encryptedString = $ this ->cipher ->encrypt ($ string );
2730
28- return $ this ->encoder ->encode (' <ENC> ' . $ encryptedString . ' </ENC> ' );
31+ return $ this ->encoder ->encode (self :: START_TAG . $ encryptedString . self :: END_TAG );
2932 }
3033
3134 public function decrypt (#[SensitiveParameter] string $ string ): string
@@ -36,13 +39,20 @@ public function decrypt(#[SensitiveParameter] string $string): string
3639 return $ string ;
3740 }
3841
39- preg_match ('/^<ENC>(.*)<\/ENC>$/ ' , $ data , $ matches );
40-
41- return $ this ->cipher ->decrypt ($ matches [1 ]);
42+ return $ this ->cipher ->decrypt ($ this ->extractTaggedValue ($ data ));
4243 }
4344
4445 private function shouldDecrypt (string $ string ): bool
4546 {
46- return preg_match ('/^<ENC>(.*)<\/ENC>$/ ' , $ string ) === 1 ;
47+ return str_contains ($ string , self ::START_TAG ) && str_contains ($ string , self ::END_TAG );
48+ }
49+
50+ private function extractTaggedValue (string $ string ): string
51+ {
52+ $ startPos = strpos ($ string , self ::START_TAG );
53+ $ endPos = strpos ($ string , self ::END_TAG );
54+
55+ $ startPos += strlen (self ::START_TAG );
56+ return substr ($ string , $ startPos , $ endPos - $ startPos );
4757 }
4858}
0 commit comments