开发者

Is there a method to randomize integers so that visitors can't figure out the sequence of objects

开发者 https://www.devze.com 2022-12-14 21:18 出处:网络
I have an id in the url.So normally it will be an auto number and so it will be 1,2,3,4,5,..... I don\'t want visitors to figure out the seque开发者_如何学运维nce and so i want to let the number be k

I have an id in the url. So normally it will be an auto number and so it will be 1,2,3,4,5,.....

I don't want visitors to figure out the seque开发者_如何学运维nce and so i want to let the number be kinda of random. So i want 1 to be converted to 174891 and 2 to 817482 and so on. But i want this to be in a specique range like 1 to 1,000,000.

I figured out i can do this using xoring and shifting of the bits of the integer. But i was wondering if this already was implemented in some place.

Thanks


You could pass your integer as the seed to a random number generator. (Just make sure that it would be unique)

You could also generate the SHA-512c hash of the integer and use that instead.

However, the best thing to do here is to use a GUID instead of an integer.

EDIT: If it needs to be reversible, the correct way to do it is to encrypt the number using AES or a different encryption algorithm. However, this won't result in a number between one and a million.


Don't rely on obscurity -- i.e., non-sequential ids -- for security. Build your app so that even if someone does guess the next id, it's still secure.

If you do need non-sequential ids, though. Generate a new id each time randomly. Store that in your table as a indexed (uniquely) column along with your autogenerated primary key id. Then all you need to do is a look up on that column to get back the real id.


EDIT: In general, I prefer tvanfosson's approach on both scores. However, here's an answer to the question as stated...

These are fairly strange design constraints, to be honest - but they're reasonably easy to deal with:

  1. Pick an arbitrary RNG seed which you will use on every execution of your program
  2. Create an instance of Random using that seed
  3. Create an array of integers 1..1000000
  4. Shuffle the array using the Random instance
  5. Create a "reverse mapping" array by going through the original array like this:

       int[] reverseMapping = new int[mapping.Length];
       for (int i = 0; i < mapping.Length; i++)
       {
            reverseMapping[mapping[i]] = i + 1;
       }
    

Then you can map both ways. This does rely on the algorithm used by Random not changing, admittedly... if that's a concern, you could always generate this mapping once and save it somewhere.


If you're looking for a fairly simple pseudo-random integer sequence, the linear congruential method is pretty good:

ni+1 = (a×ni + k) mod m

Use prime numbers for a and k.

0

精彩评论

暂无评论...
验证码 换一张
取 消