加密和解密例子

 1 # -*- coding:utf-8 -*-
 2 
 3 def extract(line, sep=' '):
 4     
 5     line = line.strip()
 6     line = line.upper()
 7     words = line.split(sep)
 8     #print(words)
 9     
10     if line == '':
11         return 'Missing key!','Missing text!'
12     elif len(words) == 1 and words[0] != '':
13         key = words[0]
14         return key,'Missing text!'
15     elif len(words) == 2:
16         key = int(words[0])
17         word = words[1]
18         return key,word
19 
20 
21 def encrypted(key, word):
22     result = ''
23     length = 26
24     for item in word:
25         index = ord(item)
26         tmp = index - 65 + key
27         
28         tmp = tmp % 26
29         char = chr(tmp+65)
30         
31         result = result + char
32     return result
33 
34 def deencrypted(key, ciphertext):
35     result = ''
36     length = 26
37     for item in ciphertext:
38         index = ord(item)
39         tmp = index-65-key
40         tmp = (tmp + 26)%26
41         char = chr(tmp+65)
42         result = result + char
43     return result
44 
45 def main():
46     
47     #filename = input('Enter the input filename:')
48     filename = 'secret_code.txt'
49 
50     if len(filename) > 0:
51         with open(filename, 'r') as file:
52             data = file.readlines()
53             for line in data:
54                 key,word = extract(line,sep=' ')
55                 #print('key={} word={}'.format(key, word))
56                 if key=='Missing key!' and word == 'Missing text!':
57                     continue
58                 
59                 if word == 'Missing text!':
60                     print('Missing text!')
61                     
62                 if key != 'Missing key!' and word != 'Missing text!':
63                     print(deencrypted(key, word))
64 
65 if __name__ == '__main__':
66     main()

 

转载于:https://www.cnblogs.com/wylwyl/p/10339185.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值