用java写一个凯撒加密工具类
时间: 2024-05-29 10:02:13 浏览: 14
好的,以下是一个用Java实现的凯撒加密工具类:
public class CaesarCipher {
private int shift;
public CaesarCipher(int shift) {
this.shift = shift;
}
public String encrypt(String input) {
StringBuilder output = new StringBuilder();
for (char c : input.toCharArray()) {
if (Character.isLetter(c)) {
char base = Character.isLowerCase(c) ? 'a' : 'A';
output.append((char) ((c - base + shift) % 26 + base));
} else {
output.append(c);
}
}
return output.toString();
}
public String decrypt(String input) {
StringBuilder output = new StringBuilder();
for (char c : input.toCharArray()) {
if (Character.isLetter(c)) {
char base = Character.isLowerCase(c) ? 'a' : 'A';
output.append((char) ((c - base - shift + 26) % 26 + base));
} else {
output.append(c);
}
}
return output.toString();
}
}
使用方法如下:
CaesarCipher cipher = new CaesarCipher(3);
String input = "HELLO WORLD";
String encrypted = cipher.encrypt(input);
String decrypted = cipher.decrypt(encrypted);
System.out.println("Input: " + input);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
输出结果如下:
Input: HELLO WORLD
Encrypted: KHOOR ZRUOG
Decrypted: HELLO WORLD