我想创建一个字母表,其中每个字母和字符都有特定的值。
例子:
A="99_banana"
a="@_melon"
B="22_GRAPE"
b="orange"
C="Strawberry"
c="life"
@="12399"
!="tv_12"
等等等等。
当我运行脚本时:
对句子进行编码:
$ ./Encryptfruits -c "Abc!"
output: 99_bananaorangelifetv_12
解码句子:
$ ./Encryptfruits -d "99_bananaorangelifetv_12"
output: Abc!
有人有例子吗?我在谷歌上搜索但没有找到任何结果
-c 参数加密
-d参数解密
答案1
在 bash 中这并不容易,但可以使用关联数组来完成。
#! /bin/bash
declare -A crypt=(
[A]="99_banana"
[a]="@_melon"
[B]="22_GRAPE"
[b]="orange"
[C]="Strawberry"
[c]="life"
['@']="12399"
['!']="tv_12"
)
encode () {
local word=$1
for ((i=0; i<${#word}; ++i)) ; do
local char=${word:$i:1}
printf %s ${crypt[$char]}
done
printf '\n'
}
declare -A decrypt
for char in "${!crypt[@]}" ; do
key=${crypt[$char]}
decrypt[$key]=$char
done
decode () {
local word=$1
while [[ $word ]] ; do
local code
for code in "${!decrypt[@]}"; do
if [[ $word == "$code"* ]] ; then
printf %s "${decrypt[$code]}"
word=${word#"$code"}
fi
done
done
printf '\n'
}
encrypted=$(encode 'Abc!')
decode "$encrypted"
请注意,如果一个字符的加密是另一字符加密的子字符串,则此操作可能会被破坏。
答案2
#! /bin/bash
declare -A crypt=(
[A]="99_banana"
[a]="@_melon"
[B]="22_GRAPE"
[b]="orange"
[C]="Strawberry"
[c]="life"
[' ']="space"
['@']="12399"
['!']="tv_12"
)
encode () {
local word=$1
for ((i=0; i<${#word}; ++i)) ; do
local char=${word:$i:1}
printf %s ${crypt[$char]}
done
printf '\n'
}
declare -A decrypt
for char in "${!crypt[@]}" ; do
key=${crypt[$char]}
decrypt[$key]=$char
done
decode () {
local word=$1
while [[ $word ]] ; do
local code
for code in "${!decrypt[@]}"; do
if [[ $word == "$code"* ]] ; then
printf %s "${decrypt[$code]}"
word=${word#"$code"}
fi
done
done
printf '\n'
}
encrypt=$(encode 'Abc !')
decrypt=$(decode "$encrypt")
echo "$encrypt"
echo "$decrypt"
我只是添加了变量以使其更容易理解