Home > Enterprise >  Basic obfuscation algorithm for integer
Basic obfuscation algorithm for integer

Time:09-24

I'm looking from some kind of obfuscation bidirectional algorithm, that maps integer (in a range, like [0 , 2^10]) to a string, to avoid URL manipulation

I see here that is suggested to generate a random string and use that as ID, but I need to associate this string to already existing data, thing that I would not consider that scalable, since I would have to generate the string for 400k entries... and furthermore, I can't encrypt it since I need this to be stored in a NFC tag, and so the memory is very limited

For the moment, I'm converting int to UUID, but at the end of the day, this changes anything, it's just the int value with some 0s as paddings

Are there anything like this?

The use cause would be:

mywebsite.com/something/1
# becomes
mywebsite.com/something/{string n char long}

where I can convert that string to int and the other way around, so there is no "easy way" for someone to go to mywebsite.com/something/2

I just need an idea, but if someone has already something like this in PHP, thank you

CodePudding user response:

As mentioned in comments, obscurity is not security. But, here is an idea that is easily reversable:

Convert to base 36 (or maybe base 35 to be less predictable)

function obfuscate(int $id) : ?string
{
    return $id
      ? strtolower(str_pad(base_convert($id, 10, 36),4,'0', STR_PAD_LEFT))
      : null;
}

function unobfuscate(?string $code) : ?int
{
    return $code
      ? base_convert($code, 36, 10)
      : null;
}


$numbers = [0,1,2,3,4,200,400,560,1000,1234567];
$obscure = [];
foreach($numbers as $number) {
    $obscure[] =  obfuscate($number);
    print obfuscate($number) . "\n";
}

foreach($obscure as $code) {
    print unobfuscate($code) . "\n";
}

// yields:
0001
0002
0003
0004
005k
00b4
00fk
00rs
qglj

1
2
3
4
200
400
560
1000
1234567

To obfuscate it more, you could add random decoy letters/numbers to the beginning or end. (I'll let you work out the details on that)

Beware though, you could end up with some urls that are not family-friendly ;)

working sample here: http://sandbox.onlinephpfunctions.com/code/d16a81c9e07c5e26ed4045d6363bbe41763470f0

I couldn't resist... 26 character working sample here: http://sandbox.onlinephpfunctions.com/code/61c919b7e294fa96377f2fe0edddb874a9a4b9ba

  • Related