python凱撒加解密

前言

密碼學實驗

代碼

算法只簡單的移位

import os

def encryption():
    m = input("請輸入明文:")
    k =int(input("位移值:"))
    s = m.lower()
    l = list(s)
    st = l
    i = 0
    while i < len(l):
        if ord(l[i]) < 123-k:
            st[i] = chr(ord(l[i]) + k)
        else:
            st[i] = chr(ord(l[i]) + k - 26)
        i = i+1
    print ("加密結果爲:"+"".join(st))
def decryption():
    m= input("請輸入密文:")
    k = int(input("位移值:"))
    s = m.lower()
    l = list(s)
    st = l
    i = 0
    while i < len(l):
        if ord(l[i]) >= 97+k:
            st[i] = chr(ord(l[i]) - k)
        else:
            st[i] = chr(ord(l[i]) + 26 - k)
        i = i+1
    print ("解密結果爲:"+"".join(st))
while True:
    encryption()
    decryption()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章