凯撒密码在php中实现

凯撒密码简介
凯撒密码是一种替换加密技术,通过将字母表中的每个字母移动固定位数实现加密。例如,位移为3时,"A"会变成"D","B"变成"E"。

PHP实现加密函数
function caesarEncrypt($text, $shift) {
$result = "";
$length = strlen($text);
for ($i = 0; $i < $length; $i++) {
$char = $text[$i];
if (ctype_upper($char)) {
$result .= chr((ord($char) + $shift - 65) % 26 + 65);
} else if (ctype_lower($char)) {
$result .= chr((ord($char) + $shift - 97) % 26 + 97);
} else {
$result .= $char;
}
}
return $result;
}
PHP实现解密函数
解密是加密的逆过程,只需将位移值取反:
function caesarDecrypt($text, $shift) {
return caesarEncrypt($text, 26 - $shift);
}
使用示例
$originalText = "HelloWorld";
$shift = 3;
$encrypted = caesarEncrypt($originalText, $shift);
echo "加密后: " . $encrypted . "\n";
$decrypted = caesarDecrypt($encrypted, $shift);
echo "解密后: " . $decrypted . "\n";
注意事项
- 该实现仅处理字母字符,数字和符号保持不变
- 位移值应介于1到25之间
- 对于非字母字符,函数会原样输出
- 大写和小写字母分别处理,保持原始大小写
扩展改进建议
- 添加对数字的加密支持
- 实现自定义字符集处理
- 增加输入验证,确保位移值有效
- 添加多字节字符支持(如UTF-8)






