我正在尝试用Python制作一个凯撒密码。我写的代码试图使用数组然后它将按重量的数量重新排列。我是一个错误所以任何关于如何使阵列系统工作的建议都得到了认可。这个想法是否有效或者我应该放弃这种方法。谢谢 如果数字不是= 1-26
,我正在重新启动的关键子程序中出现的错误import sys
Alphbet =["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"]
def Menu():
print("Welcome To Password Protect Pc Optimizer 3000 Edition!")
print("\n")
print("1.) Encrypt A New Password And Save It")
print("2.) Access An Existing Saved Password ")
print("3.) Just A One Off Encryption ")
print("4.) Quit Password Protect ")
Answer= input("Please Enter An Option Number:")
if Answer=="1":
Key()
elif Answer==2:
Option2()
elif Answer==3:
Option3()
elif Answer==4:
Quit()
else:
Menu()
def Key():
global Key
Key = input("Please Set A Ceaser Cihper Key (1-26)")
Validation =1
if Key ==1:
Validation +=1
Option1()
删除了很多elif's Here
elif Key ==26:
Validation +=1
Option1()
if Validation ==1:
print("Please Enter A Valid Number")
Key()
def Option1():
Hold=["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18
","19","20","21","22","23","24","25","26"]
for i in range(Key):
Temp= Alphabet[Hold]
Alphabet[Hold]= Alphabet[Hold-1]
Alphabet[Hold-1] =Temp
print(Alphabet)
Menu()'
答案 0 :(得分:1)
这是一个简化版本:
from collections import deque
import string
class CaesarCypher(object):
def __init__(self, cypher):
encrypt_rotate = deque(string.ascii_lowercase)
encrypt_rotate.rotate(-cypher)
decrypt_rotate = deque(string.ascii_lowercase)
decrypt_rotate.rotate(cypher)
encrypt_trans = ''.join(encrypt_rotate)
decrypt_trans = ''.join(decrypt_rotate)
self.encrypt_table = str.maketrans(string.ascii_lowercase, encrypt_trans)
self.decrypt_table = str.maketrans(string.ascii_lowercase, decrypt_trans)
def encrypt(self, text):
return text.translate(self.encrypt_table)
def decrypt(self, text):
return text.translate(self.decrypt_table)
首先导入deque
以使用其rotate
方法移动元素位置,然后导入包含字母表的string
,这样我们就不必声明它了。
然后创建一个类来封装加密和解密方法。定义一个__init__
方法,这样该类将为cypher设置一个参数,并准备将移动字符的转换表。
最后在类中添加2个方法,根据转换表加密和解密。
现在您可以这样使用您的课程:
caesar = CaesarCypher(5)
test = caesar.encrypt('Hello World!')
print(test)
# > 'Hjqqt Wtwqi!'
test2 = caesar.decrypt(test)
print(test2)
# > 'Hello World!'
编辑:
此示例仅处理小写字母,如果要加密大写字母,则需要为string.ascii_uppercase
声明一个单独的表,并在解密和加密方法上翻译文本两次,首先是低于上限。
Edit2:如果您使用的是python 2.7,maketrans
方法位于string
上,不在str
中。感谢@ t.m.adam的评论。