一、什么是凱撒密碼
“在密碼學中,愷撒密碼(英語:Caesar cipher),或稱愷撒加密、愷撒變換、變換加密,是一種最簡單且最廣為人知的加密技術,它是一種替換加密的技術,明文中的所有字母都在字母表上向后(或向前)按照一個固定數目進行偏移后被替換成密文,例如,當偏移量是3的時候,所有的字母A將被替換成D,B變成E,以此類推,這個加密方法是以羅馬共和時期愷撒的名字命名的,當年愷撒曾用此方法與其將軍們進行聯系,”
關于凱撒密碼的詳細介紹:愷撒密碼_百度百科
二、python實作凱撒加密
凱撒密碼程式的源代碼 :
在檔案編輯器中建立.py檔案,并將其保存為caesarCipher.py,然后將本文配套資源
中的pyperclip.py模塊放在與 caesarCipher.py 檔案相同的目錄(相同的檔案夾)中、
caesarCipher.py將匯入這個模塊,pyperclip.py模塊如下:
凱撒密碼的pyperclip.py模塊_??ξ李的臟臟星?的博客-CSDN博客
1.首先參考pyperclip.py模塊:
import pyperclip
2.定義變數message,message為要加密的字串:
# The string to be encrypted
message = 'ILOVEYOU.'
3.將偏移設為3,即令key=3,設定為解密模式,并加入所有可加密的符號:
# The encryption key:
key = 3
mode = 'decrypt'
# Every possible symbol that can be encrypted:
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
4. translated儲存資訊的解密形式,僅加密/解密在symbols和SYMBOLS里共有的字符(串)
# Stores the encrypted/decrypted form of the message:
translated = ''
for symbol in message:
# Note: Only symbols in the `SYMBOLS` string can be encrypted/decrypted.
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
5.執行加密/解密并添加未加密/解密的字符:
# Perform encryption/decryption:
if mode == 'encrypt':
translatedIndex = symbolIndex + key
elif mode == 'decrypt':
translatedIndex = symbolIndex - key
# Handle wrap-around, if needed:
if translatedIndex >= len(SYMBOLS):
translatedIndex = translatedIndex - len(SYMBOLS)
elif translatedIndex < 0:
translatedIndex = translatedIndex + len(SYMBOLS)
translated = translated + SYMBOLS[translatedIndex]
6.輸出translated字串:
print(translated)
pyperclip.copy(translated)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/311995.html
標籤:其他
