php和python实现凯撒密码加密解密

凯撒密码

第一次用语言实现类似的密码算法,还是挺有意思的。

php写的比较粗糙,在可以实现加解密后便觉得没有意思了,还要用python再写一遍,所以也就没有去优化之类的。

凯撒密码

算法核心:字母推移N位

代码

python解密

1
2
3
4
5
6
7
8
9
10
11
key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
encode = 'PELCGBTENCUL';
for item in range(1,26):
temp_str = "Try %.2d " % item
for value in encode:
# 字母转数字
up_char_n = key.find(value)-item
up_char = key[up_char_n]
temp_str += up_char
print(temp_str)

php解密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
$key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key_array = str_split($key,1);

$key_array_v = array_flip($key_array);

$encode = 'PELCGBTENCUL';

$encode_array = (str_split($encode,1));
// # 26个字母
for ($i=0; $i <26 ; $i++) {
echo('Try '.sprintf("%'02d",$i).' ');
foreach ($encode_array as $key => $value) {
# 提前N位
$up_char_n = $key_array_v[$value]-$i;
# 字母循环
$up_char_n = $up_char_n<0?$up_char_n +=26:$up_char_n;
# 数字转字母
$up_char = $key_array[$up_char_n];
echo(($up_char));
}
echo(PHP_EOL);
}
// CRYPTOGRAPHY

python加密

1
2
3
4
5
6
7
8
9
10
11
12
key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
code = 'CRYPTOGRAPHY';
for item in range(1,26):
temp_str = "Try %.2d " % item
for value in code:
# 字母转数字
up_char_n = key.find(value)+item
if up_char_n > 25:
up_char_n -= 26
up_char = key[up_char_n]
temp_str += up_char
print(temp_str)

php加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
$key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key_array = str_split($key,1);

$key_array_v = array_flip($key_array);

$encode = 'PELCGBTENCUL';

$encode_array = (str_split($encode,1));
// # 26个字母
for ($i=0; $i <26 ; $i++) {
echo('Try '.sprintf("%'02d",$i).' ');
foreach ($encode_array as $key => $value) {
# 提前N位
$up_char_n = $key_array_v[$value]+$i;
# 字母循环
$up_char_n = $up_char_n>25?$up_char_n -=26:$up_char_n;
# 数字转字母
$up_char = $key_array[$up_char_n];
echo(($up_char));
}
echo(PHP_EOL);
}