How can I encrypt/decrypt 12-digit decimal numbers to other ones, using a password and Java?

后端 未结 12 1171
再見小時候
再見小時候 2020-12-15 15:12

I have already read Using Java to encrypt integers and Encrypting with DES Using a Pass Phrase.

All I need is a simple Encrypter which transforms a 12 digit number t

12条回答
  •  孤街浪徒
    2020-12-15 15:29

    I suggest a very simple algorithm.

    1. Feed the password into a hash function.
    2. Initialize a random number generator with the hash or something you derived from the hash.
    3. Generate a 12 digit random number.
    4. Add this random number to the input digit by digit modulo 10 to encrypt.

    To decrypt subtract the random number modulo 10. This is actually a form of One Time Pad. Because of the comments on this answer I realized that refering to One Time Pad was a bad choice. A better reference is Polyalphabetic cipher - while One Time Pad uses polyalphabetic substitution its main characteristic is not to use any key bit twice.

       Input           1234 1234 1234
       Random number   6710 3987 2154
       Output          7944 4111 3388
    

    There is one remaining problem with that - the algorithm might create leading zeros. To solve this problem one could use XOR instead of addition and substraction. Just transform the digits with XOR. If the first digit turns into a zero, don't encrypt the first digit. When you decrypt with XOR again, the first digit will turn into zero and you know that the first digit was not enrcypted.

    UPDATE

    A simple XOR is not the solution because it will produce to large numbers - 2 XOR 9 = 11 for example. Going to rethinks this...

    UPDATE

    The nice propoerties of XOR are XOR(a, b) = XOR(b, a) and XOR(XOR(a, b), b) = a. This makes encryption and decryption the same and allows to detect the unencrypted leading digit. But it is further required that our function only returns values in the range from 0 to 9 what XOR doesn't do.
    But maybe we can build a custom function with all required properties. So we create an array FUNC with 10 columns and 10 rows and use it as a lookup table for our function. What values to but in? I actually don't know - I am not even sure that it is possible. But if we pick three number from the range 0 to 9 we have to make the following six entries. (It is a symmetric matrix.)

    FUNC[x,y] = z   FUNC[x,z] = y   FUNC[y,z] = x
    FUNC[y,x] = z   FUNC[z,x] = y   FUNC[z,y] = x
    

    So maybe it is possible to create such a function by repeatedly choosing random numbers and filling the six entries if there is no conflict. Maybe it is not. I would like to see the table if one finds a solution.

提交回复
热议问题