什么是凯撒密码?
凯撒密码是一种古典密码,也称作移位密码。
它是通过将明文中的每个字母按照指定的偏移量进行移位来加密的。
例如,如果偏移量为3,则字母A将被加密为D,字母B将被加密为E,以此类推。
解密过程则是将加密后的密文按照相同的偏移量进行反向移位,得到原始的明文。
代码
//这里是加密函数
public static String encrypt(String ciphertext, int offset) {
return CaesarCipher(ciphertext, offset);
}
//这里是解密函数
public static String decrypt(String ciphertext, int offset) {
return CaesarCipher(ciphertext, -offset);
//只需加一个负号即可解密
}
/*
加密/解密函数
凯撒密码的加密和解密代码是一样的,只需要把偏移量改为负数
输入
plaintext:明文String
offset:偏移量int
输出密文String
*/
public static String CaesarCipher(String plaintext, int offset) {
StringBuilder ciphertext = new StringBuilder();
for (int i = 0; i < plaintext.length(); i++) {
char c = plaintext.charAt(i);
// 只对字母进行偏移
if (Character.isLetter(c)) {
// 大写字母偏移
if (Character.isUpperCase(c)) {
c = (char) ((c - 'A' + offset) % 26 + 'A');
}
// 小写字母偏移
else {
c = (char) ((c - 'a' + offset) % 26 + 'a');
}
}
ciphertext.append(c);
//合并
}
return ciphertext.toString();
//输出
}
举报 0