python实现的Caesar加解密算法
发布时间:2020-05-25 00:08:17 所属栏目:Python 来源:互联网
导读:python实现的Caesar加解密算法
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 # Caeser Cipher
import sys,os
MyCypher = 25
MyDict = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz `[emailprotected]#$%^&*()_+[];',./{}|:"<>?'
plaintext = 'Hello World!'
cryptmsg = ''
def encrypt(text,cypher):
out_text = ''
for e in text:
x = e
if (e in MyDict):
idx = MyDict.find(e)
idx = idx + cypher
idx = idx % len(MyDict)
x = MyDict[idx]
out_text = "%s%c" % (out_text,x)
return out_text
def decrypt(msg,cypher):
out_text = ''
for e in msg:
x = e
if (e in MyDict):
idx = MyDict.find(e)
idx = idx - cypher + len(MyDict)
idx = idx % len(MyDict)
x = MyDict[idx]
out_text = "%s%c" % (out_text,x)
return out_text
def ask_cypher():
user_input = raw_input('Input Cypher: ')
return long(user_input)
def ask_text():
user_input = raw_input('Input Text: ')
return user_input
def ask_action():
print '-----------------------'
print '0 - Exit'
print '1 - Encrypt'
print '2 - Decrypt'
print '-----------------------'
user_input = raw_input('Select You Action: ')
if user_input in ['0','1','2']:
if user_input == '0':
return 'exit'
elif user_input == '1':
return 'enc'
elif user_input == '2':
return 'dec'
else:
return 'exit'
# ---------------------------------------------------------------
# Program Start Here
# ---------------------------------------------------------------
MyCypher = ask_cypher()
print 'Cypher: %d' % MyCypher
for i in range(0,100):
action = ask_action()
if action == 'dec':
cryptmsg = ask_text()
print decrypt(cryptmsg,MyCypher)
elif action == 'enc':
plaintext = ask_text()
print encrypt(plaintext,MyCypher)
else:
print 'Exit!'
break
执行后,输入密码(数字),然后选择动作,最后输入密文或原文,就能得到原文或密文了. 以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
