換位加密算法

換位加密

不是把字符替換成其他字符,而是搞亂消息符號的順序,使原來的消息不可讀。

算法大意

明文爲:Common sense is not so common.
一行爲8個格子,寫入字符,超出則下一行。(空白字符以 ( ) 表示)

1 2 3 4 5 6 7 8
C o m m o n s
e n s e i s
n o t s o c
o m m o n .

忽略 ‘.’ 右邊兩個空 數據
從左往右,從上往下則可以形成
密文:Cenoonommstmme oo snnio. s s c

代碼實例

import math
# 換位加密算法
def encryptMessage(key,message):
    # 申請二維數組存放密文數組
    ciphertxt = [''] * key
    for col in range(key):
        # 初始化指針位置 並且初始化密文數組位置
        pointer = col
        while pointer < len(message):
            #每隔相同間隔提取一個數據組成一個數組
            ciphertxt[col] += message[pointer]
            # 指針指向下一個數據間隔爲key
            pointer += key
    # 將二維數組組成一串字符串
    return ''.join(ciphertxt)

# 換位解密算法
def decryptMessage(key,message):
    # 通過密鑰獲得列數
    numOfColumns = math.ceil(len(message)/key)
    # 密鑰及行數
    numOfRows = key
    # 計算多餘的空數據個數
    numOfShadeBoxes = (numOfColumns * numOfRows) - len(message)
    # 由於解密數據依然是從上到下,從左至右讀取,所以二維數組申請爲 1*列數
    plaintext = [''] * numOfColumns
    col = 0
    row = 0
    for symol in message:
        plaintext[col] += symol
        col += 1
        # 橫座標到了範圍外或者縱座標到最後一列且行數到了下一個是空數據時 
        if(col == numOfColumns) or (col == numOfColumns -1 and row >= numOfRows - numOfShadeBoxes):
            col = 0
            row += 1
    return ''.join(plaintext)


def main_e():
    myMessage = 'Common sense is not so common.'
    myKey = 8
    ciphertxt = encryptMessage(myKey,myMessage)
    print(ciphertxt + '|')

def main_d():
    myMessage = 'Cenoonommstmme oo snnio. s s c'
    myKey = 8
    plaintext = decryptMessage(myKey,myMessage)
    print(plaintext + '|')

if __name__ == "__main__":
    main_e()
    main_d()

運行結果

Cenoonommstmme oo snnio. s s c|
Common sense is not so common.|

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章