0

I don't want to return raw user IDs to the frontend. A lot of people solve this by generating random IDs and checking if they're already in the DB. I want to find a way to map numbers in a known range 1 to 1. This way, I can still use auto-incremented IDs internally, but return the pseudorandomly mapped IDs to the frontend.

I could just shuffle all numbers from 1 to N in a deterministic way, but I'm wondering if there's a more efficient way.

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • Have you considered UUID? https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript – Jay Mar 10 '20 at 23:27
  • UUIDs are what I described, you generate a random number and check if it's already in the DB, I'd prefer a cleaner mathematical way to do it – Leo Jiang Mar 10 '20 at 23:29
  • 3
    The easiest way is to put the number through some block cipher. Block ciphers are essentially keyed shuffle functions. – bennofs Mar 10 '20 at 23:54

1 Answers1

-1

You can pick a random number and use bitwise XOR operations to switch between frontend and database IDs.

It would probably be easy to reverse engineer, but it's very easy to use.

Here's an example in JavaScript:

const seed = 123;
const internalIds = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(internalIds.join(','));
const frontIds = internalIds.map(id => id ^ seed);
console.log(frontIds.join(','));
const recoveredIds = frontIds.map(id => id ^ seed);
console.log(recoveredIds.join(','));
Stratubas
  • 2,939
  • 1
  • 13
  • 18