java實現加密-位加密解密演算法
阿新 • • 發佈:2021-11-19
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class demo { static char[] bitcode(char[] str, char n) //位加密解密演算法 { int i, len; char[] wen; len = str.length; if ((wen = newchar[len + 1]) == null) { System.out.print("申請記憶體失敗!\n"); System.exit(1); } for (i = 0; i < len; i++) { wen[i] = (char) (str[i] ^ n); //異或運算 } wen[len] = '\0'; return wen; } public static void main(String[] args) throwsIOException { int i; char ch; char[] srcstr = new char[100]; char[] miwen; String go; System.out.print("位加密解密演算法演示!\n"); do { System.out.print("\n請先輸入替換加密解密演算法中的金鑰:"); Scanner input = new Scanner(System.in); ch= input.next().charAt(0); //金鑰 System.out.print("請輸入明文字串:"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String str = bufferedReader.readLine(); srcstr = str.toCharArray(); //明文字串 System.out.print("輸入的明文為:"); for (i = 0; i < srcstr.length; i++) { System.out.print(srcstr[i]); } miwen = bitcode(srcstr, ch); //加密 System.out.print("\n加密後的密文為:"); for (i = 0; i < srcstr.length; i++) { System.out.print(miwen[i]); } miwen = bitcode(miwen, ch); //解密 System.out.print("\n解密出的明文為:"); for (i = 0; i < srcstr.length; i++) { System.out.print(miwen[i]); } System.out.print("\n繼續執行(y/n)?"); go = input.next(); } while (go.equalsIgnoreCase("y")); System.out.println("演示結束!"); } }