一文詳解凱撒密碼的原理及Python實現(xiàn)
一、什么是愷撒密碼
愷撒密碼是古羅馬愷撒大帝用來對軍事情報進行加密的算法,它采用了替換方法對信息中的每一個英文字符循環(huán)替換為字母表序列該字符后面第三個字符:
原文: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
密文:D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
原文字符P,其密文字符C滿足如下條件:
C = ( P + 3 ) mod 26
解密方法反之,滿足:
P = ( C – 3 ) mod 26
二、程序運行環(huán)境
程序運行環(huán)境是:pycharm2021
三、愷撒密碼:加密
愷撒密碼的加密算法程序首先接收用戶輸入的文本
然后對字母a-z和字母A-Z按照密碼算法進行轉(zhuǎn)換
3.1 愷撒密碼加密實例程序
# 愷撒密碼加密 def Caesar_PW_Encryption(): inputText = input("請輸入明文文本: ") for index in inputText: if "a" <= index <= "z": print(chr(ord("a") + (ord(index) - ord("a") + 3) % 26), end='') elif "A" <= index <= "Z": print(chr(ord("A") + (ord(index) - ord("A") + 3) % 26), end='') else: print(index, end='')
在主函數(shù)中調(diào)用這個Caesar_PW_Encryption愷撒密碼加密函數(shù),如下所示
if __name__ == '__main__': # 愷撒密碼加密 Caesar_PW_Encryption()
3.2 愷撒密碼加密實例程序運行結(jié)果
四、愷撒密碼:解密
愷撒密碼的解密算法程序首先接收用戶輸入的加密文本
然后對字母a-z和字 母A-Z按照密 碼算法進行反向轉(zhuǎn)換
4.1 愷撒密碼解密實例程序
# 愷撒密碼解密 def Ceasar_PW_Decryption(): inputText = input("請輸入加密后文本: ") for index in inputText: if "a" <= index <= "z": print(chr(ord("a") + (ord(index) - ord("a") - 3) % 26), end='') elif "A" <= index <= "Z": print(chr(ord("A") + (ord(index) - ord("A") - 3) % 26), end='') else: print(index, end='')
在主函數(shù)中調(diào)用這個Caesar_PW_Encryption愷撒密碼加密函數(shù),如下所示
if __name__ == '__main__': # 愷撒密碼加密 Caesar_PW_Encryption() # 愷撒密碼解密 Ceasar_PW_Decryption()
4.2 愷撒密碼解密實例程序運行結(jié)果
五、完整程序
# 愷撒密碼加密 def Caesar_PW_Encryption(): inputText = input("請輸入明文文本: ") for index in inputText: if "a" <= index <= "z": print(chr(ord("a") + (ord(index) - ord("a") + 3) % 26), end='') elif "A" <= index <= "Z": print(chr(ord("A") + (ord(index) - ord("A") + 3) % 26), end='') else: print(index, end='') # 愷撒密碼解密 def Ceasar_PW_Decryption(): inputText = input("請輸入加密后文本: ") for index in inputText: if "a" <= index <= "z": print(chr(ord("a") + (ord(index) - ord("a") - 3) % 26), end='') elif "A" <= index <= "Z": print(chr(ord("A") + (ord(index) - ord("A") - 3) % 26), end='') else: print(index, end='') if __name__ == '__main__': # 愷撒密碼加密 Caesar_PW_Encryption() # 愷撒密碼解密 Ceasar_PW_Decryption()
六、總結(jié)
本文主要講解了愷撒密碼:采用了替換方法對信息中的每一個英文字符循環(huán)替換為字母表序列該字符后面第三個字符。并通過一個實例程序來進一步加強對愷撒密碼的理解與運用。
以上就是一文詳解凱撒密碼的原理及Python實現(xiàn)的詳細內(nèi)容,更多關(guān)于Python凱撒密碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
已安裝tensorflow-gpu,但keras無法使用GPU加速的解決
今天小編就為大家分享一篇已安裝tensorflow-gpu,但keras無法使用GPU加速的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python實現(xiàn)嵌套列表及字典并按某一元素去重復(fù)功能示例
這篇文章主要介紹了Python實現(xiàn)嵌套列表及字典并按某一元素去重復(fù)功能,涉及Python列表嵌套列表、列表嵌套字典,及按照某一元素去重復(fù)的相關(guān)操作方法,需要的朋友可以參考下2017-11-11Python中字符串String的基本內(nèi)置函數(shù)與過濾字符模塊函數(shù)的基本用法
這篇文章主要介紹了Python中字符串String的基本內(nèi)置函數(shù)與過濾字符模塊函數(shù)的基本用法 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05