From 3de4abfac03c860946ec76038ebc00951f4befd9 Mon Sep 17 00:00:00 2001 From: Lakkes Ra <63732644+lakkes-ra@users.noreply.github.com> Date: Thu, 30 May 2024 21:06:16 +0200 Subject: [PATCH] [5.x] Use multibyte methods for obfuscate (#10201) Co-authored-by: Jason Varga --- src/Support/Html.php | 10 ++++------ tests/Modifiers/ObfuscateTest.php | 32 +++++++++++++++++++++++++++---- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/Support/Html.php b/src/Support/Html.php index 7ad16e9906..b3fa78094c 100644 --- a/src/Support/Html.php +++ b/src/Support/Html.php @@ -219,20 +219,18 @@ public static function obfuscate($value) { $safe = ''; - foreach (str_split($value) as $letter) { - if (ord($letter) > 128) { - return $letter; - } + foreach (mb_str_split($value) as $letter) { + $ordValue = mb_ord($letter); // To properly obfuscate the value, we will randomly convert each letter to // its entity or hexadecimal representation, keeping a bot from sniffing // the randomly obfuscated letters out of the string on the responses. switch (rand(1, 3)) { case 1: - $safe .= '&#'.ord($letter).';'; + $safe .= '&#'.$ordValue.';'; break; case 2: - $safe .= '&#x'.dechex(ord($letter)).';'; + $safe .= '&#x'.dechex($ordValue).';'; break; case 3: $safe .= $letter; diff --git a/tests/Modifiers/ObfuscateTest.php b/tests/Modifiers/ObfuscateTest.php index 0c6185fb69..5a4e4ffa9d 100644 --- a/tests/Modifiers/ObfuscateTest.php +++ b/tests/Modifiers/ObfuscateTest.php @@ -7,11 +7,35 @@ class ObfuscateTest extends TestCase { - /** @test */ - public function it_obfuscates_a_string(): void + /** + * @test + * + * @dataProvider seedProvider + */ + public function it_obfuscates_strings($seed, $value, $expected) { - $modified = $this->modify('A'); - $this->assertTrue(in_array($modified, ['A', 'A', 'A'])); + mt_srand($seed); // make rand predictable for testing. + + $this->assertEquals($expected, $this->modify($value)); + + srand(); // reset to not affect other tests. + } + + public static function seedProvider() + { + return [ + 'A, case 1' => [1, 'A', 'A'], + 'A, case 2' => [2, 'A', 'A'], + 'A, case 3' => [5, 'A', 'A'], + + 'é, case 1' => [1, 'é', 'é'], + 'é, case 2' => [2, 'é', 'é'], + 'é, case 3' => [5, 'é', 'é'], + + '🐘, case 1' => [1, '🐘', '🐘'], + '🐘, case 2' => [2, '🐘', '🐘'], + '🐘, case 3' => [5, '🐘', '🐘'], + ]; } private function modify($value)