zoukankan      html  css  js  c++  java
  • 加密和解密例子

     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()
  • 相关阅读:
    查找链表中是否有环linked-list-cycle
    reverse-integer
    AVL树之 Java的实现
    single-number
    Best Time to Buy and Sell Stock II
    maximun-depth-of-binary-tree
    minimun-depth-of-binary-tree
    剑指offer--矩阵中的路径
    grep的几个参数
    fsck和badlocks
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10339185.html
Copyright © 2011-2022 走看看