列移位密码解密(Decryption of the Columnar Transposition Cipher)的Pyhton实现

结果最近在做一道列移位密码的解密的题目时,想借助在线工具解密,发现解密时,工具对密文中的数字以及符号进行了过滤。造成了:明文的长度 小于 密文的长度的情况,后来,在Python的Cipher库中,也发生的相同的情况。

考虑编写代码,使用密钥对密文进行解密:

密文:
Ciphertext= "{ad1b!gb9a7!f3b73!f3458bl16d4ca2322}b026a!"
密钥:
key="gksbate"
填充字符:
paddingcharacter="!"

恢复过程如下:

g k s b a t e
4 5 6 2 1 7 3
f l a g { b f
3 1 2 b a 0 3
4 6 3 9 d 2 b
5 d 2 a 1 6 7
8 4 2 7 b a 3
b c } ! ! ! !

代码如下:

# 1、手动输入
# Ciphertext=input("cryptedText:")
# key=input("key:")
# paddingcharacter=input("padding character:")

# 2、示例1
# Ciphertext="qouryinphoTkoolhbxvauwmtdcfsegerjez"
# key="howareu"
# paddingcharacter="!"

Ciphertext= "{ad1b!gb9a7!f3b73!f3458bl16d4ca2322}b026a!" #密文
key="gksbate" # 密钥
paddingcharacter="!" #填充字符

print (Ciphertext)
keylength=len(key)
index=[]
list=[]
for i in key:
    list.append(i)
list.sort()
for i in key:
    index.append(list.index(i))
print (index)
plaintext=""
Round=int(len(Ciphertext) / keylength)
print (Round)
for i in range(Round):
    for j in range(keylength):
        # print (Round*index[j]+i)
        ch=Ciphertext[Round * index[j] + i]
        plaintext+=ch
        # if ch is not paddingcharacter:
        #     plaintext+=ch
        # else:
        #     plaintext+=''
print(plaintext)
Num_Of_padding=0 #统计填充字符个数
while (plaintext[len(Ciphertext) - Num_Of_padding - 1]) is paddingcharacter:
    Num_Of_padding+=1
    # print( Num_Of_padding)
print (plaintext[:-Num_Of_padding])

结果如下: 

{ad1b!gb9a7!f3b73!f3458bl16d4ca2322}b026a!
[3, 4, 5, 1, 0, 6, 2]
6
flag{bf312ba034639d2b5d2a1678427ba3bc}!!!!
flag{bf312ba034639d2b5d2a1678427ba3bc}

Process finished with exit code 0

你可能感兴趣的:(密码学,python,密码学)