用shell编写一个凯撒密码的加解密脚本
时间: 2023-09-18 09:09:45 浏览: 50
以下是一个用Shell编写的凯撒密码加解密脚本:
```shell
#!/bin/bash
# 凯撒密码加解密脚本
# 加密函数
encrypt() {
local plaintext="$1"
local shift="$2"
local ciphertext=""
for (( i=0; i<${#plaintext}; i++ )); do
char="${plaintext:$i:1}"
if [[ "$char" =~ [a-z] ]]; then
ciphertext+="$(echo $char | tr "a-z" "$(printf %${shift}s | tr " " ".;\\[/")a-z")"
elif [[ "$char" =~ [A-Z] ]]; then
ciphertext+="$(echo $char | tr "A-Z" "$(printf %${shift}s | tr " " ".;\\[/")A-Z")"
else
ciphertext+="$char"
fi
done
echo "$ciphertext"
}
# 解密函数
decrypt() {
local ciphertext="$1"
local shift="$2"
local plaintext=""
for (( i=0; i<${#ciphertext}; i++ )); do
char="${ciphertext:$i:1}"
if [[ "$char" =~ [a-z] ]]; then
plaintext+="$(echo $char | tr "$(printf %${shift}s | tr " " ".;\\[/")a-z" "a-z")"
elif [[ "$char" =~ [A-Z] ]]; then
plaintext+="$(echo $char | tr "$(printf %${shift}s | tr " " ".;\\[/")A-Z" "A-Z")"
else
plaintext+="$char"
fi
done
echo "$plaintext"
}
# 主程序
if [[ "$1" == "encrypt" ]]; then
plaintext="$2"
shift="$3"
if [[ -z "$plaintext" || -z "$shift" ]]; then
echo "Usage: $0 encrypt <plaintext> <shift>"
exit 1
fi
ciphertext="$(encrypt "$plaintext" "$shift")"
echo "$ciphertext"
elif [[ "$1" == "decrypt" ]]; then
ciphertext="$2"
shift="$3"
if [[ -z "$ciphertext" || -z "$shift" ]]; then
echo "Usage: $0 decrypt <ciphertext> <shift>"
exit 1
fi
plaintext="$(decrypt "$ciphertext" "$shift")"
echo "$plaintext"
else
echo "Usage: $0 {encrypt|decrypt} <text> <shift>"
exit 1
fi
```
使用方法:
1. 将以上脚本保存为 `caesar.sh` 文件。
2. 在终端中执行以下命令使脚本可执行:`chmod +x caesar.sh`
3. 对明文进行加密:`./caesar.sh encrypt "明文" 3`,其中 `3` 表示移位数。
4. 对密文进行解密:`./caesar.sh decrypt "密文" 3`,其中 `3` 表示移位数。
注意:以上脚本只支持英文字符的加解密。如果需要支持其他语言或字符集,请根据需要进行修改。