凯撒加密法

时光毁灭记忆、已成空白 提交于 2020-02-15 22:05:36

凯撒加密法

根据密钥以不同方式加密消息,密钥是从0到25的整数。

算法大意

将明文通过有序替换的方式变成密文,
及将明文在密文字典的位置加上密钥数值后锁定密文字典里的新文字就成了密文。
此方法缺点就是当知道了字典后可以尝试暴力破解。

代码实例

# 密文字典
global LETTERS
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# 加密算法
def cliper(msg,mode,key):
    msg = msg.upper()
    translated = ''
    for symbol in msg:
        if symbol in LETTERS:
            num = LETTERS.find(symbol)
            if mode =='encrypt':
                num = num + key
            elif mode == 'decrypt':
                num = num - key
            if num >= len(LETTERS):
                num = num - len(LETTERS)
            elif num < 0 :
                num = num + len(LETTERS)
            translated = translated + LETTERS[num]
        else:
            translated = translated + symbol
    return translated

# 明文加密
message = 'This is my secret message.'
# 密钥为13
translated = cliper(message,mode = 'encrypt',key = 13)
print(translated)
# 密文解密
clipertxt = translated
txt = cliper(clipertxt,'decrypt',key = 13)
print(txt)


# 暴力破解算法
def decipher(msg):
    msg = msg.upper()
    for key in range(len(LETTERS)):
        translated = ''
        for symbol in msg:
            if symbol in LETTERS:
                num= LETTERS.find(symbol)
                num = num - key
                if num < 0:
                    num = num + len(LETTERS)
                translated = translated + LETTERS[num]
            else:
                translated = translated + symbol
        print(translated)
print('------暴力破解密文--------')
decipher(clipertxt)

运行结果

GUVF VF ZL FRPERG ZRFFNTR.
THIS IS MY SECRET MESSAGE.
------暴力破解密文--------
GUVF VF ZL FRPERG ZRFFNTR.
FTUE UE YK EQODQF YQEEMSQ.
ESTD TD XJ DPNCPE XPDDLRP.
DRSC SC WI COMBOD WOCCKQO.
CQRB RB VH BNLANC VNBBJPN.
BPQA QA UG AMKZMB UMAAIOM.
AOPZ PZ TF ZLJYLA TLZZHNL.
ZNOY OY SE YKIXKZ SKYYGMK.
YMNX NX RD XJHWJY RJXXFLJ.
XLMW MW QC WIGVIX QIWWEKI.
WKLV LV PB VHFUHW PHVVDJH.
VJKU KU OA UGETGV OGUUCIG.
UIJT JT NZ TFDSFU NFTTBHF.
THIS IS MY SECRET MESSAGE.
SGHR HR LX RDBQDS LDRRZFD.
RFGQ GQ KW QCAPCR KCQQYEC.
QEFP FP JV PBZOBQ JBPPXDB.
PDEO EO IU OAYNAP IAOOWCA.
OCDN DN HT NZXMZO HZNNVBZ.
NBCM CM GS MYWLYN GYMMUAY.
MABL BL FR LXVKXM FXLLTZX.
LZAK AK EQ KWUJWL EWKKSYW.
KYZJ ZJ DP JVTIVK DVJJRXV.
JXYI YI CO IUSHUJ CUIIQWU.
IWXH XH BN HTRGTI BTHHPVT.
HVWG WG AM GSQFSH ASGGOUS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!