python实现的Caesar加解密算法

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

Caesar算法是最简单的加解密算法...

    # Caeser Cipher  
      
    import sys,os  
      
    MyCypher = 25  
      
    MyDict = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz `1234567890-=~!@#$%^&*()_+[]\\;\',./{}|:"<>?'  
      
    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  

执行后,输入密码(数字), 然后选择动作, 最后输入密文或原文, 就能得到原文或密文了.

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:C#编程读取文档Doc,Docx,Pdf的内容

下一篇:Apache HttpClient 连接池的使用