密码学学习(二) 置换加密算法(Transposition Cipher)及python实现

来源:互联网 发布:js获取 鼠标位置 编辑:程序博客网 时间:2024/05/29 08:27

置换加密算法

加密

比如我们想要加密的明文是
Common sense is not so common.
并且取key为8
首先,把明文写成每行key个字符,也就是8个字符的形式,空格也算一个字符Common(s)sense(s)is(s)not(s)so(s)common.  然后从左往右把每一列的字母从上到下写成一排,得到
Cenoonommstmme oo snnio s s c
这就是加密后的密文 :)

python实现
# !python3.3def TranspositionCipher(key, message):    """    @param key: a positive number used for encryption    @param message: the plain text needs encryption    @return: the encrypted text    """    if key <= 0: # the algorithm can't work        return message     else:        return "".join([message[i::key] for i in range(key)])

解密

在之前的加密过程中,得到了key = 8,密文是
Cenoonommstmme oo snnio s s c
把字符串长度除以key
30/8 = 3.75
取上整,得4
然后,用key作为行数,4作为列数画一个表格
                                然后,计算8*4 - 30 = 2
所以把最后一行的最后两个格子划去,从上到下用密文填满整个表格
Cenoonommstmme(s)oo(s)snnio.(s)s(s)划去s(s)c划去然后从左到右把每一列的字符写出来,得到明文
Common sense is not so common.

python实现(不漂亮)
def DecryptTranspositionCipher(key, message):    """    @param key: a positive number used for encryption    @param message:  the encrypted message    @return: plaintext    """    import math    numOfColumns = math.ceil(len(message) / key)    numOfRows = key    numOfShadeBoxes = (numOfColumns * numOfRows) - len(message)    plaintext = [''] * numOfColumns        col = 0    row = 0    for symbol in message:        plaintext[col] += symbol        col += 1        if (col == numOfColumns) or (col == numOfColumns-1 and row>=numOfRows-numOfShadeBoxes):            col = 0            row += 1    return ''.join(plaintext)


原创粉丝点击