将字符简单后移
package sample.demo;
/**
* @author lh
* @date 2021/12/29 12:38
*/
public class CaesarDemo {
private static String encrypt(String clearText, int key) {
char[] chars = clearText.toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] += key;
}
return new String(chars);
}
public static void main(String[] args) {
String clearText = "adasd";
int key = 3;
String cipher = encrypt(clearText, key);
System.out.println(cipher);
String derypt = decrypt(cipher, key);
System.out.println(derypt);
}
private static String decrypt(String cipher, int key) {
char[] chars = cipher.toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] -= key;
}
return new String(chars);
}
}