fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. }
  14. }
Success #stdin #stdout 0.06s 54604KB
stdin
import java.util.Scanner;

/**
 * 实验1:利用异或实现字符串加密和解密
 */
public class EncryptXOR {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // 1. 输入明文和密钥
        System.out.print("请输入明文:");
        String plainText = sc.nextLine();

        System.out.print("请输入密钥字符:");
        char key = sc.nextLine().charAt(0);

        // 2. 加密
        String cipherText = encrypt(plainText, key);
        System.out.println("加密后的密文:" + cipherText);

        // 3. 解密(异或两次还原)
        String decryptText = encrypt(cipherText, key);
        System.out.println("解密后的明文:" + decryptText);

        sc.close();
    }

    // 加密/解密通用方法(异或一次加密,异或两次解密)
    public static String encrypt(String text, char key) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            // 逐个字符异或
            char c = (char) (text.charAt(i) ^ key);
            sb.append(c);
        }
        return sb.toString();
    }
}
stdout
Standard output is empty