views:

335

answers:

1

I'm trying to add a small level of security to a site and encode some ids. The id's are already a concat of linked table rows, so storing the encryption in the db isn't very efficient. Therefore I need to encode & decode the string.

I found this great little function from myphpscripts, and I'm wondering what the chances are of collisions.

I really don't know much about these sorts of things. I'm assuming that the longer my key, the less collisions i'm going to have.

I could end up with more than 10 million unique concatenated ids, and want to be sure I'm not going to run into issues.

function encode($string,$key) {
    $key = sha1($key);
    $strLen = strlen($string);
    $keyLen = strlen($key);
    $j=0;
    $hash='';
    for ($i = 0; $i < $strLen; $i++) {
        $ordStr = ord(substr($string,$i,1));
        if ($j == $keyLen) { $j = 0; }
        $ordKey = ord(substr($key,$j,1));
        $j++;
        $hash .= strrev(base_convert(dechex($ordStr + $ordKey),16,36));
    }
    return $hash;
}
+4  A: 

I think you are a bit confused about this issue.

The problem of collisions only applies to mappings that are not 1-to-1, but "lossy", i.e. map several different inputs to one ouput (such as hashes).

What you linked to looks like an encryption/decryption routine (if it works correctly, which I didn't check). Encryption by definition means that there is a matching decryption, hence the mapping defined by the encryption cannot have collisions (as you could not decrypt in that case).

So your question, as posted, does not make sense.

That said, I would strongly suggest you do not use bandaids like encrypting IDs. Just store the IDs server-side and generate a session key to refer to them.

sleske
ForerMedia
@ForerMedia: the only part that is Sha1'd is the key for salting the encryption. I have tried the encrypt/decrypt, and it does work on the pieces i've tried.
pedalpete
my apologies to all then
ForerMedia
@pedalpete: I bumped you up a point for teaching me a lesson :)
ForerMedia
@sleske: I see what you mean (kinda) and now that I look at it closer and with a bit more of your insight, I'll have to agree that they will stay unique, but I disagree re:session keys. This isn't a session based key. It is two strings (keys) put together which I just don't want to pass visibly. As mentioned they are linked through tables and I currently just put the strings together for the request id. But I'd rather not use that so visibly in the URL, so I'm trying to do some simple encryption.
pedalpete
That was just my point: Don't put anything private into the URL, "encrpyted" or not. Just generate a (random!) session key to put into the URL, and store the data server-side under the session key. That way the URL does not expose anything, and messing with it gets you nowhere. Standard procedure, really.
sleske