我是密码学的新手,所以我尝试使用python创建一个简单的Caesar密码程序 但它只会返回一个字母。有人可以帮忙吗?这是我的代码:
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
答案 0 :(得分:0)
您的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)