There is no reason to ever want this. Some people think it adds something to security. They're absolutely wrong. Don't be one of those people.
If you absolutely must do something like this, own it. Generate a table that has 4.2 billion ids and randomize the order of it.
CREATE TABLE stupid_false_security(id, stupidId)
row_number() OVER (ORDER BY random()) AS stupidId
ORDER BY id;
I think any of these methods are at least a step in the right direction, they're less insane.
- hashids takes your number and returns a nifty alphanumeric id that resolves to it.
- base64/base32 encoding
Comparison with Jack Douglas's Answer
Using the MATHS there is an idea called a surjective function. It means you're mapping one domain onto another domain. Here is an example in decimal:
f(x) = x + y; --impure y
x = truncate(f(x));
Is true for all integers of
x such that
0<y<1. So if you simply truncate down you can get back to
x. This doesn't add any security,
f(42) = 42.4
f(42) = 42.000001
f(42) = 42.0588
f(42) = 42.48787
Given the output, what is
x for all of these? Hint: It's 42. Jack's answer pick's a random
y adds it to the input in the same fashion (but in binary) and stores it in the database. If that's what you want, then have at it (also may be important to point out that Jack's sequence is also ordinal with one coming after the other even if it's non-consecutive).
My answer takes a list of all values in the domain of int4. Randomizes the order, and stores them in a table. Without that table you can never get back to your original sequential ids: it's just a shallow and useless obfuscation table that you'll like ditch or not implement because it's pretty silly. But you can never get the original value without that table.