[英]Caesar cipher python error
我是密碼學的新手,所以我嘗試用 python 制作一個簡單的凱撒密碼程序,但它只返回一個字母。 有人可以幫忙嗎? 這是我的代碼:
def main():
text = raw_input('input plainteks:')
key = int(raw_input('input key:'))
print("plain teks :"+text)
print("key :" +str(key))
print("hasil cipher:", encrypt(text,key))
def encrypt(text,key):
hasil = ''
for i in range(len(text)): #
char = text[i]
if (char.isupper()):
hasil += chr((ord(char) + key-65)%26 + 65)
else:
hasil += chr((ord(char) + key-97)%26 + 97)
return hasil
當我嘗試運行它時:
input plainteks:melody
input key:3
plain teks :melody
key :3
hasil cipher: b
你的if
不在循環中。 以下代碼有效:
def main():
text = raw_input('input plainteks:')
key = int(raw_input('input key:'))
print("plain teks: "+text)
print("key: " +str(key))
print("hasil cipher: "+encrypt(text,key))
def encrypt(text,key):
hasil = ''
for i in range(len(text)): #
char = text[i]
if (char.isupper()):
hasil += chr((ord(char) + key-65)%26 + 65)
else:
hasil += chr((ord(char) + key-97)%26 + 97)
return hasil
main()
您也可以使用secretpy
模塊
from secretpy import Caesar
text = 'melody'
key = 3
print(text)
cipher = Caesar()
enc = cipher.encrypt(text, key)
print(enc)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.