7

I want to develop something similar to jsfiddle in where the user can input some data and then "save" it and get a unique random looking url that loads that data.

I don't want to make the saves sequential because I don't want anyone to grab all of my entries, as some can be private. However on the server I would like to save it in sequential order.

Is there a function or technique that converts a number into a hash that has 4 charactors without any collisions until (62 * 62 * 62 * 62 === 14776336) entries?

For example the first entry on the server will be named 1 on the server but iUew3 to the user, the next entry will be 2 on the server but ueGR to the user...

EDIT: I'm not sure if it's obvious but this hash-like function needs to be reversible because when the user requests ueGR the server needs to know to server it file 2

qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • 2
    If I was doing this, then I'd probably be using a different programming language and so could use [the Crypt::Skip32::Base32Crockford module](https://metacpan.org/module/Crypt::Skip32::Base32Crockford) which says it *lets you have numeric database records ids which you can use safely in URLs without letting users see how many records you have or letting them jump forward or backwards between records*. The source code is available though, so you can port the algorithm to PHP if you like. – Quentin Mar 21 '12 at 12:09
  • 2
    Why do you need it to be reversible? Just store the generated hash with the id and your done. – Yoshi Mar 21 '12 at 12:19
  • @Yoshi: I'm not using a database – qwertymk Mar 21 '12 at 12:33
  • 2
    Oh, then I guess you'll have to look for a crypt function (like Quentin suggests) instead of a hash function. – Yoshi Mar 21 '12 at 12:35
  • A hash function is by definition not reversible. – harold Mar 21 '12 at 12:37
  • What _are_ you using to store the data, if not a database? – Nick Johnson Mar 22 '12 at 17:09
  • @NickJohnson: individual files. – qwertymk Mar 22 '12 at 18:13
  • @qwertymk So why do IDs need to be sequential? Just name the files after the hash. Also, why on earth aren't you using a database? They're built for this. – Nick Johnson Mar 23 '12 at 07:50
  • @harold: http://en.wikipedia.org/wiki/Hash_function#Trivial_hash_function and http://en.wikipedia.org/wiki/Hash_function#Perfect_hashing – Karoly Horvath Mar 24 '12 at 09:47
  • @KarolyHorvath they're not really reversible either, they're only reversible when there's some limitation on the input. – harold Mar 24 '12 at 10:44
  • @harold: have you actually read it? you often have a limitation on the input. the OP also gave a limit. check my answer. – Karoly Horvath Mar 24 '12 at 10:54
  • @KarolyHorvath I admit I haven't – harold Mar 24 '12 at 10:57

6 Answers6

8

It's possible to do this, but I would suggest using 64 characters, as that will make it a lot easier. 4 6bit characters = 24bits.

Use a combination of these:

  • bit reordering
  • xor with a number
  • put it into a 24bit maximal length LFSR and do a couple of cycles.

LFSR is highly recommended as it will do a good scrambling. The rest are optional. All of these manipulations are reversible and guarantee that each output is going to be unique.

When you calculated the "shuffled" number simply pack it to a binary string and encode it with base64_encode.

For decoding simply do the inverse of these operations.

Sample (2^24 long unique sequence):

function lfsr($x) {
    return ($x >> 1) ^ (($x&1) ? 0xe10000 : 0);
}
function to_4($x) {
    for($i=0;$i<24;$i++)
        $x = lfsr($x);
    $str = pack("CCC", $x >> 16, ($x >> 8) & 0xff, $x & 0xff);
    return base64_encode($str);
}

function rev_lfsr($x) {
    $bit = $x & 0x800000;
    $x = $x ^ ($bit ? 0xe10000 : 0);
    return ($x << 1) + ($bit ? 1 : 0);
}
function from_4($str) {
    $str = base64_decode($str);
    $x = unpack("C*", $str);
    $x = $x[1]*65536 + $x[2] * 256 + $x[3];
    for($i=0;$i<24;$i++)
        $x = rev_lfsr($x);
    return $x;
}

for($i=0; $i<256; $i++) {
    $enc = to_4($i);
    echo $enc . " " . from_4($enc) . "\n";
}

Output:

AAAA 0
kgQB 1
5ggD 2
dAwC 3
DhAH 4
nBQG 5
6BgE 6
ehwF 7
HCAO 8
jiQP 9
+igN 10
aCwM 11
EjAJ 12
gDQI 13
9DgK 14
ZjwL 15
OEAc 16
qkQd 17
3kgf 18
TEwe 19
NlAb 20
pFQa 21
0FgY 22

...

Note: for URL replace + and / with - and _.

Note: although this works, for a simple scenario like yours it's probably easier to create a random filename, till it doesn't exist. nobody cares about the number of the entry.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • @Khorvath. That's an excellent solution! Would it be possible to scale those functions to form an 11 character string to encoded IDs in a similar fashion to the video IDs included in the v $_GET variable in YouTube's URLs, i.e. RArlg6HeZZM in http://www.youtube.com/watch?v=RArlg6HeZZM? – Barry Beerman Aug 23 '13 at 15:44
  • 1
    @BarryBeerman: Yes it's possible. For any practical size. You have to alter the code a bit though. The wikipedia article links this: http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf It has solutions for maximal length LFSR taps for up to 168 bits. – Karoly Horvath Aug 25 '13 at 18:13
  • @Khorvath: That's perfect. If you get a chance, would you be able to answer this question http://stackoverflow.com/questions/18365607/generating-youtube-esque-ids-with-an-lfsr-in-php with a code example so I can accept it? Thanks again for your help. – Barry Beerman Aug 26 '13 at 12:12
  • @Khorvath: I can add a bounty if that helps. I've just seen a lot of attempts at creating an algorithm that's similar to YouTube's video id encryption and your approach is easily the best. – Barry Beerman Aug 30 '13 at 11:42
1

In my opinion if you also keeping the save time of entry on server, you can generate a hash function. hash = func(id, time) but with only hash = func(id) gonna be to easy to resolve

safarov
  • 7,793
  • 2
  • 36
  • 52
1

Here's how I implemented it. Here's the save.php file (can someone tell me if there are any design flaws in it):

<?php

$index = file_get_contents('saves/data/placeholder');
$index++;
file_put_contents('saves/data/placeholder', $index);

$string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
do {
    $hash = $string[rand(0, 61)] . $string[rand(0, 61)] . $string[rand(0, 61)] . $string[rand(0, 61)];
} while (file_exists('saves/' . $hash));

file_put_contents('saves/' . $hash, $index);
file_put_contents('saves/data/' . $index, $_REQUEST['data']);

echo $hash;

?>

And here's load.php:

<?php

if (!file_exists('saves/' . $_REQUEST['file'])) {
    file_put_contents('saves/data/log', 'requested saves/' . $_REQUEST['file'] . "\n", FILE_APPEND);
    die();
}
$file_pointer = file_get_contents('saves/' . $_REQUEST['file']);

if (!file_exists('saves/data/' . $file_pointer)) {
    file_put_contents('saves/data/log', 'requested saves/data/' . $file_pointer . 'from ' . $_REQUEST['file'] . "\n", FILE_APPEND);
    die();
}
echo file_get_contents('saves/data/' . $file_pointer);

?>

Hope this helps others.

qwertymk
  • 34,200
  • 28
  • 121
  • 184
0

Here's a reversible lib that works w/ bcmath
http://blog.kevburnsjr.com/php-unique-hash

KevBurnsJr
  • 4,869
  • 2
  • 25
  • 16
0

It's an odd set of constraints. I routinely use MD5 checksums to generate unique URLs from data. If the user doesn't already have the data, they can't guess the URLs.

I do understand about not wanting to use a database—if you've never used one before, the learning curve can be a little steep.

I don't understand the constraint about "storing things sequentially on the server." If you need to know the order in which the hashes are created, I'd simply put that information in a separate file. You might have to do file locking or some other kind of hack to make sure you can append a hash to that file incrementally.

If you want short URLs, you can either take a prefix of an MD5 checksum or you can take a CRC-32 and base64 encode it. Both will give you unique URLs with reasonably good probability.

Norman Ramsey
  • 198,648
  • 61
  • 360
  • 533
  • the last paragraph is a bad suggestion, you can create collisions with it. – Karoly Horvath Mar 24 '12 at 01:43
  • @KarolyHorvath, I know, but OP specified short URLs. I've actually had good success with CRC-32 checksums; the probability of collision is small. But when I want something close to a guarantee, I just use full MD5 and live with the long URLs – Norman Ramsey Mar 24 '12 at 03:01
-1

This can't really be reversible. The only way (the one used by url shorteners and jsfiddle) is to store the generated hash (actually it's a digest) in a table/data structure of some sort and *look it up on retrieval.

Why this?

Passing from, e.g. 128 chars of data → a 4 visible char digest, you lose a lot of data.
You cannot store the remaining data in the magical cracks betweeen those 4 bytes, there are none.

ZJR
  • 9,308
  • 5
  • 31
  • 38
  • 1
    "converts a number into a hash that has 4 charactors without any collisions until (62 * 62 * 62 * 62 === 14776336) entries" - there is no loss of data. – Karoly Horvath Mar 24 '12 at 01:41