Java 实现凯撒密码
时间: 2023-11-14 07:37:36 浏览: 89
凯撒密码凯撒密码,zip
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.isUpperCase(c) ? 'A' : 'a';
c = (char) (((c - base + shift) % 26) + base);
}
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.isUpperCase(c) ? 'A' : 'a';
c = (char) (((c - base - shift + 26) % 26) + base);
}
output.append(c);
}
return output.toString();
}
}
// Example usage:
CaesarCipher cipher = new CaesarCipher(3);
String encrypted = cipher.encrypt("Hello, world!");
System.out.println(encrypted); // "Khoor, zruog!"
String decrypted = cipher.decrypt(encrypted);
System.out.println(decrypted); // "Hello, world!"
阅读全文