Exclusive or operation for encryption and decryption
In an exclusive or operation, if a character (or value) x and a value m perform an exclusive or operation to obtain y, then use y and m to perform an exclusive or operation to restore x, therefore, this principle can be used to encrypt and decrypt data.
Exclusive or operations usually have two common methods in java. One is the interchange of two variables (without the third variable), and the other is the simple encryption and decryption of data.
Interchange of two variables
In java operations, if you want to exchange the values of two variables, the common practice is to use the third temporary variable and then complete the operation.
For example
Public static void main (String [] args) {int [] arr = {1, 6, 4, 2, 3, 8, 9, 10 }; for (int I = 0; I
In the preceding example, the inverted operation of the array is completed. The two-position data exchange in the array is completed by using the swapNumber method.With the help of the Temporary Variable temp, The swapNumber method first assigns the value of arr [x] to the Temporary Variable temp, and then assigns arr [y] To arr [x], finally, assign temp to arr [y].
If the temporary variables temp are not allowed in the request and data exchange between the x and y locations is still required, what should we do? An exception or operation can be used.
Now we change the above program to an exclusive or operation to exchange the variable values at the x and y positions.
public static int[] swapNumber(int[] arr, int x, int y) {arr[x] = arr[x] ^ arr[y];arr[y] = arr[y] ^ arr[x];arr[x] = arr[x] ^ arr[y];return arr;}
Encryption and decryption
Public static void main (String [] args) {// password civilized String str = "hello world"; // data encryption process System. out. println (decode (str); // You can decrypt the System by encrypting the encrypted ciphertext. out. println (decode (str);} public static String decode (String str) {char [] array = str. toCharArray (); for (int I = 0; IThe encryption operation of the encryption method is to perform an exclusive or operation on each character in the string, and then return the string after the exclusive or operation to obtain the ciphertext.
Based on the principle that "the XOR operation between character (or value) x and a value m is used to obtain y, then the XOR operation between y and m can be restored to x, perform an exclusive or operation on each character in the password to obtain the previous plaintext information and decrypt it.
In the example, the (decode (str) method implements the encryption process, and the encrypted ciphertext can be decrypted again, that is, decode (str )).