Java 实现凯撒密码
时间: 2023-11-14 13:37:36 浏览: 47
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!"
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)