Simple data encryption and decryption
The character string is usually encrypted by the exclusive or operation of "^"
Get the character array through char[] array = String.toCharArray(); / / and;
Then traverse the character array for exclusive or operation
The operation of exclusive or by bit is: 1 for the same bit value, 0 for the different bit value
The original text and the key are XOR to get the ciphertext, which is encryption
The original text can be obtained by exclusive or operation of ciphertext and the same key, which is decryption
The code is as follows:
1 import java.io.*; 2 3 public class Example { 4 public static void main(String[] args) { 5 char a[] = "I'm really super handsome".toCharArray(); 6 int n = 0; 7 try { 8 File out = new File("word.txt"); 9 for (int i = 0; i < a.length; i++) { 10 a[i] = (char) (a[i] ^ 'R'); 11 } 12 FileWriter fw = new FileWriter(out); 13 fw.write(a, 0, a.length); 14 fw.close(); 15 FileReader fr = new FileReader(out); 16 char tom[] = new char[10]; 17 System.out.println("After encryption:"); 18 while ((n = fr.read(tom, 0, 10)) != -1) { 19 String s = new String(tom, 0, n); 20 System.out.println(s); 21 } 22 fr.close(); 23 fr = new FileReader(out); 24 System.out.println("Plaintext:"); 25 while ((n = fr.read(tom, 0, 10)) != -1) { 26 for (int j = 0; j < n; j++) { 27 tom[j] = (char) (tom[j] ^ 'R'); 28 } 29 String str = new String(tom, 0, n); 30 System.out.println(str); 31 } 32 33 fr.close(); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 38 } 39 40 }
The encrypted result is as follows: