如何使python加密大写和小写?

时间:2014-01-29 21:57:15

标签: python python-3.x case-sensitive encryption

基本上我希望加密的短语作为输出,大写字母被加密为大写,小写字母被加密为小写,但没有任何空格或符号被加密。它可以加密包含所有大写的段落和包含所有小写但不包含两者的段落。这就是我所拥有的。

def encrypt(phrase,move):
encription=[]
for character in phrase:
    a = ord(character)
    if a>64 and a<123:
        if a!=(91,96):
            for case in phrase:
                        if case.islower():
                            alph=["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"]
                            dic={}
                            for i in range(0,len(alph)):
                                dic[alph[i]]=alph[(i+move)%len(alph)] 
                                cipherphrase=""  
                            for l in phrase:  
                                if l in dic:  
                                    l=dic[l]  
                                cipherphrase+=l
                                encription.append(chr(a if 97<a<=122 else 96+a%122))
                            return cipherphrase
                        else:
                            ALPH=["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"]
                            DIC={}
                            for I in range(0,len(ALPH)):
                                DIC[ALPH[I]]=ALPH[(I+move)%len(ALPH)]
                                cipherphrase=""
                            for L in phrase:
                                if L in DIC:
                                    L=DIC[L]
                                cipherphrase+=L
                                encription.append(chr(a if 97<a<=122 else 96+a%122))
                            return cipherphrase

我知道很多,但你可以看到我不是很好

2 个答案:

答案 0 :(得分:2)

import string
def rot_cipher(msg,amount):
    alphabet1 = string.ascii_lowercase + string.ascii_uppercase
    alphabet2 = string.ascii_lowercase[amount:] + string.ascii_lowercase[:amount]\
                + string.ascii_uppercase[amount:] + string.ascii_uppercase[:amount]
    tab = str.maketrans(alphabet1,alphabet2)
    return msg.translate(tab)

print(rot_cipher("hello world!",13))

答案 1 :(得分:2)

import string

def caesar_cipher(msg, shift):
    # create a character-translation table
    trans = dict(zip(string.lowercase, string.lowercase[shift:] + string.lowercase[:shift]))
    trans.update(zip(string.uppercase, string.uppercase[shift:] + string.uppercase[:shift]))

    # apply it to the message string
    return ''.join(trans.get(ch, ch) for ch in msg)

然后

caesar_cipher('This is my 3rd test!', 2)     # => 'Vjku ku oa 3tf vguv!'