1. 程式人生 > >密碼學學習(二) 置換加密演算法(Transposition Cipher)及python實現

密碼學學習(二) 置換加密演算法(Transposition Cipher)及python實現

置換加密演算法

加密

比如我們想要加密的明文是
Common sense is not so common.
並且取key為8 首先,把明文寫成每行key個字元,也就是8個字元的形式,空格也算一個字元
C o m m o n (s) s
e n s e (s) i s (s)
n o t (s) s o (s) c
o m m o n .
然後從左往右把每一列的字母從上到下寫成一排,得到
Cenoonommstmme oo snnio s s c
這就是加密後的密文 :) python實現
# !python3.3

def 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 所以把最後一行的最後兩個格子劃去,從上到下用密文填滿整個表格
C e n o
o n o m
m s t m
m e (s) o
o (s) s n
n i o .
(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)