简体   繁体   中英

Encryption of a 6 digit number into another 6 digit number in c#

I want to encrypt an id and pass to a link..for example

id=196
encryptedid=345
randno=234
encryptedrandno=456
id=encryptedid+encryptedrandno
link: id
so when user clikcs that link at backend 
id=id-encryptedrandno(which gives us encryptedid)
id=decrypt(id)

Pls tel me this logic I am using c# web application

With three digits (now six after a question edit), you've basically got a very small source and target domain - I hope this isn't for anything important.

The simplest way of effectively creating a bimap between the values is probably to create a list of the values 0-999, and shuffle it (in some reproducible way). You'd then "encrypt" by taking the value at a particular index, and "decrypt" by finding the index of that value:

int id = ...;
int encrypted = shuffledValues[id];
int decrypted = shuffledValues.IndexOf(encrypted);

You can make the "decryption" rather quicker by building a dictionary, mind you:

Dictionary<int, int> decryptionDictionary =
    shuffledValues.Select((value, index) => new { value, index })
                  .ToDictionary(p => p.value, p => p.index);

This obviously takes more memory than a traditional encryption approach, but it's very simple to code.

Unlike almost any other security question, I think in this case it wouldn't be too bad to just use System.Random for the shuffling - but that's not because Random is usually appropriate for security uses; it's because you've got such a horribly small range of potential values to start with.

I would seriously try to move away from using 3-digit IDs.

An alternative approach would be to generate a new GUID instead. In your database, store the original ID and the generated GUID, and hand the GUID back to the client (eg on the link). When you receive a GUID, you can perform a query in the database to get the original data.

EDIT: Even 6 digits IDs aren't going to be much better than the original 3. It's easy to try every one of a million digits, so an attack can visit every possible link quickly. Fetching ten links per second, they'd be able to fetch them all in less than two days. Even with rate limiting, you're still basically far from secure.

To put it another way: if someone asked you to choose a password for a website, but said it had to just be 6 digits, how secure would you feel?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM