簡單的資料加密解密,簡單資料加密解密
簡單的資料加密解密
通常都是利用“^”異或運算對字串進行加密
通過char[] array = String.toCharArray();// 擷取字元數組;
然後遍曆字元數組,進行異或運算
按位做“異或”運算是:位值相同得1,不同得0
原文和密鑰進行異或運算得到密文,這是加密
將密文和同一密鑰進行異或運算就可以得到原文,這就是解密
代碼如下:
1 import java.io.*; 2 3 public class Example { 4 public static void main(String[] args) { 5 char a[] = "我真的超級帥".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("加密後:");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("明文:");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 }
加密後結果如下: