凱撒密碼的加密解密


凱撒密碼的加密解密

密碼.jpeg

前言

凱撒密碼作為一種最為古老的對稱加密體制,在古羅馬的時候都已經很流行,他的基本思想是:通過把字母移動一定的位數來實現加密和解密。明文中的所有字母都在字母表上向后(或向前)按照一個固定數目進行偏移后被替換成密文。例如,當偏移量是3的時候,所有的字母A將被替換成D,B變成E,以此類推X將變成A,Y變成B,Z變成C。由此可見,位數就是凱撒密碼加密和解密的密鑰。

凱撒密碼加密腳

  • 交單的26次加密腳本

#coding:utf-8

upperDict=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lowerDict=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def cesarWithLetter(ciphertext,offset):
    '''
    凱撒密碼 :
        只轉換字母(包括大寫小寫)
    參數 : 
        ciphertext : 明文
        offset : 偏移量
    '''
    result = ""
    for ch in ciphertext:
        if ch.isupper():
            result=result+upperDict[((upperDict.index(ch)+offset)%26)]
        elif ch.islower():
            result=result+lowerDict[((lowerDict.index(ch)+offset)%26)]
        elif ch.isdigit():
            result=result+ch
        else:
            result=result+ch
    return result

def printAllResult(ciphertext):
    '''
    打印所有偏移結果
    '''
    for i in range(len(upperDict)):
        print cesarWithLetter(ciphertext,i)

ciphertext=raw_input("Please input the words :")
printAllResult(ciphertext)

自動控制偏移位自動解密


#-*-coding:utf-8-*-
__author__ = 007
__date__ = 2016 / 02 / 04


#==================================================================#
#         凱撒密碼(caesar)是最早的代換密碼,對稱密碼的一種                #
#   算法:將每個字母用字母表中它之后的第k個字母(稱作位移值)替代            #
#==================================================================#

def encryption():
    str_raw = raw_input("請輸入明文:")
    k = input("請輸入位移值:")
    str_change = str_raw.lower()
    str_list = list(str_change)
    str_list_encry = str_list
    i = 0
    while i < len(str_list):
        if ord(str_list[i]) < 123-k:
            str_list_encry[i] = chr(ord(str_list[i]) + k)
        else:
            str_list_encry[i] = chr(ord(str_list[i]) + k - 26)
        i = i+1
    print "加密結果為:"+"".join(str_list_encry)

def decryption():
    str_raw = raw_input("請輸入密文:")
    k = input("請輸入位移值:")
    str_change = str_raw.lower()
    str_list = list(str_change)
    str_list_decry = str_list
    i = 0
    while i < len(str_list):
        if ord(str_list[i]) >= 97+k:
            str_list_decry[i] = chr(ord(str_list[i]) - k)
        else:
            str_list_decry[i] = chr(ord(str_list[i]) + 26 - k)
        i = i+1
    print "解密結果為:"+"".join(str_list_decry)

while True:
    print u"1. 加密"
    print u"2. 解密"
    choice = raw_input("請選擇:")
    if choice == "1":
        encryption()
    elif choice == "2":
        decryption()
    else:
        print u"您的輸入有誤!"

#if __name__ == "__main__":
#    main


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM