题目如下:
这是一种加密方式,叫做轮转密码或者叫比尔密码,解密的方式就是先通过密钥调整字符串的行号,然后通过密文调整每一行字符串的顺序,例如,密文的第一个字母是H,
第一行字符串是
KPBELNACZDTRXMJQOYHGVSFUWI
则,将H 以前的所有字符放到该字符串的末尾
HGVSFUWIKPBELNACZDTRXMJQOY
知道了解决方法,下面开始写脚本,我是先人工将字符串行号排序,放到一个txt中,然后才用脚本解密,脚本如下:
fileone = open("t.txt","r+") #手工排序行号的字符串
filetwo = open("c.txt","w+") # 新的文件保存结果
attr = "HCBTSXWCRQGLES" # 密文
attrtwo = ""
num = 0
for line in fileone:
print(len(line))
for i in line:
if i != attr[num]:
attrtwo = attrtwo + i
else:
#attrtwo = attrtwo + i
attrone = line[len(attrtwo):26]+attrtwo + "\n"
filetwo.write(attrone)
break
attrtwo = ""
num = num + 1
fileone.close()
filetwo.close()
运行脚本,生成c.txt文件,仔细观察每一列,在倒数第六列有发现:
对的,结果就是上述字符串,最后再贴上大佬写的一个脚本,不用人工排序:
#coding:utf-8
#秘钥
key="2,5,1,3,6,4,9,7,8,14,10,13,11,12"
#密文
cipher_text = "HCBTSXWCRQGLES"
f = open("1.txt")
str_first_encry = []
for line in f:
line = line.strip()
str_first_encry.append(line)
key_index = key.split(",")
str_second_encry=[]
for k in key_index:
str_second_encry.append(str_first_encry[int(k)-1])
print(str_first_encry[int(k)-1])
for i,ch in enumerate(cipher_text):
line = str_second_encry[i]
split_index = line.index(ch)
temp=[]
temp[0:len(line)-split_index+1] = line[split_index:len(line)]
temp[len(temp):] = line[0:split_index]
str_second_encry[i] = "".join(temp)
print("-------------------------------------")
for plain in str_second_encry:
print(plain)