Skip to content

Commit

Permalink
[5.x] Use multibyte methods for obfuscate (#10201)
Browse files Browse the repository at this point in the history
Co-authored-by: Jason Varga <jason@pixelfear.com>
  • Loading branch information
lakkes-ra and jasonvarga authored May 30, 2024
1 parent ef28ec4 commit 3de4abf
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
10 changes: 4 additions & 6 deletions src/Support/Html.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
32 changes: 28 additions & 4 deletions tests/Modifiers/ObfuscateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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, ['&#65;', '&#x41;', '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', '&#x41;'],
'A, case 2' => [2, 'A', '&#65;'],
'A, case 3' => [5, 'A', 'A'],

'é, case 1' => [1, 'é', '&#xe9;'],
'é, case 2' => [2, 'é', '&#233;'],
'é, case 3' => [5, 'é', 'é'],

'🐘, case 1' => [1, '🐘', '&#x1f418;'],
'🐘, case 2' => [2, '🐘', '&#128024;'],
'🐘, case 3' => [5, '🐘', '🐘'],
];
}

private function modify($value)
Expand Down

0 comments on commit 3de4abf

Please sign in to comment.