Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Short id like Youtube, with salt

I need to encode/encrypt database ids and append them to my URLs. Security is not an issue I am trying to deal with, but I am looking for something with moderate security. The main goal is to have short ids that are unique and URL-safe.

The following snippet seems like it will do what I need (from http://programanddesign.com/php/base62-encode/)

function encode($val, $base=62,  $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    // can't handle numbers larger than 2^31-1 = 2147483647
    $str = '';
    do {
        $i = $val % $base;
        $str = $chars[$i] . $str;
        $val = ($val - $i) / $base;
    } while($val > 0);
    return $str;
}

function decode($str, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    $len = strlen($str);
    $val = 0;
    $arr = array_flip(str_split($chars));
    for($i = 0; $i < $len; ++$i) {
        $val += $arr[$str[$i]] * pow($base, $len-$i-1);
    }
    return $val;
}

echo encode(2147483647); // outputs 2lkCB1

I'll probably modify the functions a bit:

  1. Remove the $base parameter; that can be figured out by strlen ($chars)
  2. Eliminate from the character set letter/numbers that can be confused for each other (e.g. 0, O, o)

How would I change the script such I can also use a salt with it? And would that be a wise idea? Would I inadvertently increase chance of collision, etc.?

like image 274
StackOverflowNewbie Avatar asked Nov 11 '10 10:11

StackOverflowNewbie


2 Answers

If you want to make the numerical id unguessable from the string, you can use a salt. You should be able to get the id back without collisions. The post Create short IDs with PHP - Like Youtube or TinyURL by Kevin van Zonneveld is a good start. At any rate, check for uniqueness.

like image 117
Halil Özgür Avatar answered Nov 03 '22 07:11

Halil Özgür


Could you not just use PHP's uniqid function to generate a faux-random string from the current timestamp? Then save this alpha-numeric string in the video record at upload time.

like image 27
Martin Bean Avatar answered Nov 03 '22 08:11

Martin Bean