sqids/sqids-php

Issue - Inconsistent Decoding with Appended Characters in Sqid

Closed this issue · 6 comments

When appending additional characters to the Sqid (Sequential ID), the decoding process consistently results in the same ID, regardless of the appended characters. For instance, if the original ID is "000," appending characters like "fsadqwop321" still yields the decoded ID as "1." This behavior appears inconsistent with the intended decoding process.

Context

I am utilizing route binding in my application to decode IDs, employing the following function:

public function decode($hash)
{
    $decoded = $this->sqids->decode($hash);
    if (empty($decoded)) {
        // Handle invalid sqids
        throw new InvalidArgumentException('Invalid hashid provided.');
    }
    return $decoded[0];
}

Expected Behavior

The decoding process should only be successful if the Sqid matches exactly. Appending additional characters should not alter the decoding result.

Steps to Reproduce

Generate a Sqid, e.g., "000."
Append random characters to the Sqid, such as "000fsadqwop321."
Decode the modified Sqid using the provided decoding function.
Observe that the decoded ID remains the same, despite the appended characters.

4kimov commented
if (empty($decoded)) {

That's not the way to check if ID is valid. Here's more info: https://sqids.org/faq#valid-ids

I think if (empty($decoded)) is possible, then encode() or encode([]) is valid

BTW, here's what the playground is doing with the reported issue:
image

I'm guessing the PHP library is returning [0] in this case instead of the error the playground is showing

4kimov commented

The playground is doing internally what the link above is suggesting: re-encoding decoded numbers to check if they match; since they don't, it's showing "Error: Invalid ID"

So in the Spec, you can just add letters at the end of the encoded string to pad it out without setting the min length?

4kimov commented

@fdomgjoni99 I'll close the issue, let me know if you still have questions.

@miquelfire Padding works by appending the separator character twice, and after that all characters are junk characters. More on it here (number 5): https://github.com/sqids/sqids-spec#-how-it-works

So in my example, bM are separators