Python 2 Caesar Cipher

时间:2014-07-12 18:27:51

标签: python encryption cryptography

我的问题是如何改进代码,以便它可以适应输入消息的长时间。按原样,消息必须为5个字母。我想改进代码,以便可以输入任意长度的消息,并且密码可以使用它。非常感谢帮助。 :-)请参阅下面的代码!

#Enter your message
message=raw_input('Enter your message here. Make sure to use all CAPS througout your message and leave no spaces in between words.')
length=len(message)
print 'The length of your message is ',length

#This statement is a possible idea to let the program know how many letters it will be need to shift. But I don't know how to actually do this.
print chr(length+64)
#Indexes letters out of message.
A=message[length-length]
B=message[length-length+1]
C=message[length-length+2]
D=message[length-length+3]
E=message[length-length+4]

#Shifts letters and accounts for shifting XYZ to ABC. 
def shift(x):
    if ord(x)+3==91:
        return 65
    if ord(x)+3==92:
        return 66
    if ord(x)+3==93:
        return 67
    else:
        return ord(x)+3

a2=shift(A)
b2=shift(B)
c2=shift(C)
d2=shift(D)
e2=shift(E)


#Converts shifted ordinals back to characters
def convert(x):
    return chr(x)
first=convert(a2)
second=convert(b2)
third=convert(c2)
fourth=convert(d2)
fifth=convert(e2)

#Prints resultant characters
print first,second,third,fourth,fifth

5 个答案:

答案 0 :(得分:2)

import string
shift_amt = 13
alphabet_lc = string.ascii_lowercase
shifted_lc = alphabet_lc[shift_amt:]+alphabet_lc[:shift_amt]

alphabet_uc = alphabet_lc.upper()  
shifted_uc = shifted_lc.upper()
trans_tab = string.maketrans(alphabet_lc+alphabet_uc,shifted_lc+shifted_uc)



message = "Encode Me To a new MessaGez!"
print message.translate(trans_tab)

至少是在Python2中实现它的一种方式

答案 1 :(得分:1)

使用两个for循环,一个用于循环遍历每个字符,另一个用于将字符移动所需的次数。我们使用函数upper()来移动角色。

def upper(char):
    from string import ascii_letters as _all
    if char == ' ':
        return ' '
    return _all[_all.index(char)+1] if char != 'Z' else 'a'

def shift(message, key):
    temp = []
    for i in message:
        char = i
        for k in range(key):
            char = upper(char)
        temp.append(char)
    return ''.join(temp)

message=raw_input('Enter your message here: ')
key = int(raw_input('Enter the desired key: '))
length=len(message)
print 'The length of your message is', length

print 'Your encrypted message is {0}'.format(shift(message, key))

运行如下:

bash-3.2$ python caesar.py
Enter your message here: This works WITH or without CAPS
Enter the desired key: 10
The length of your message is 31
Your encrypted message is drsC GyBuC gSdR yB GsDryED MKZc
bash-3.2$ 

答案 2 :(得分:1)

Ceasar密码内置于python 2;

In [6]: 'The Caesar cipher is built-in.'.encode('rot13')
Out[6]: 'Gur Pnrfne pvcure vf ohvyg-va.'

如您所见,此编码仅对字母起作用,适用于大写和小写。

但是你想删除空格并使每个事物都是大写的,Python也可以这样做;

In [9]: 'this is a string'.translate(None, ' \t')
Out[9]: 'thisisastring'

In [10]: 'this is a string'.translate(None, ' \t').upper()
Out[10]: 'THISISASTRING'

In [11]: 'this is a string'.translate(None, ' \t').upper().encode('rot13')
Out[11]: 'GUVFVFNFGEVAT'

或以不同的方式;

In [15]: ''.join('this is a string'.split()).upper().encode('rot13')
Out[15]: 'GUVFVFNFGEVAT'

答案 3 :(得分:0)

  

<强>参考书目:
  儿童片段:“数学课”(由孩子设想) - YouTube http://youtu.be/KdxEAt91D7k
  玛丽有一首小羔羊童谣歌词 - YouTube http://youtu.be/CkRdvGmcCBE
  玛丽有一只小羊羔 - 维基百科,免费的百科全书http://goo.gl/FNEuyd

Python源代码:

  

注意:也适用于负班次号
  注意:如果反向移位,那么我们编码 - 解码消息
  注意:也保留空格

small_chars = [chr(item) for item in range(ord('a'), ord('z')+1)]
upper_chars = [item.upper() for item in small_chars]

def encode_chr(chr_item, is_upper_case):
    '''
    Cipher each chr_item.
    '''
    # setting orig and end order.
    if is_upper_case:
        orig_ord = ord('A')
        end_ord  = ord('Z')
    else:
        orig_ord = ord('a')
        end_ord  = ord('z')

    # calculating shift    
    temp_ord = ord(chr_item)+shift
    # calculating offset order with modulo.
    # char is after end_ord, calculating offset
    num_of_chars = 26
    offset_ord = (temp_ord - end_ord - 1)%num_of_chars
    return chr(orig_ord + offset_ord)

# enable while loop to repeat until status not 'y'
status = 'y'
while status == 'y':
    # enter word to cipher.
    word = raw_input("Word: ")
    # enter char shift
    shift = input("Shift: ")
    print

    # create cipher list variable
    cipher = list()
    # loop trough each char in word
    for chr_item in word:
        # encode just letters.
        # replace non-alfa with underscore: "_"
        if chr_item in upper_chars or chr_item in small_chars:
            # set is_uppser_case to True for upper case chars.
            is_upper_case = (chr_item in upper_chars) and True
            # cipher char.
            temp_chr = encode_chr(chr_item, is_upper_case)
            # append ciphered char to list
            cipher.append(temp_chr)
        elif chr_item is ' ':
            cipher.append(chr_item)
        else:
            cipher.append('_')

    # print word
    print word
    # print ciphered word
    print ''.join(cipher)

    # repeat again for another word?
    status = raw_input("Repeat? [y|n]: ")
    print

测试用例:

>>> 
Word: aAzZ!@
Shift: 1

aAzZ!@
bBaA__
Repeat? [y|n]: y

Word: aAzZ@!
Shift: -1

aAzZ@!
zZyY__
Repeat? [y|n]: y

Word: aAzZ@$
Shift: 27

aAzZ@$
bBaA__
Repeat? [y|n]: y

Word: aAzZ%^
Shift: -27

aAzZ%^
zZyY__
Repeat? [y|n]: n

>>> 

输出:

  

注意:如果反向移位,那么我们编码 - 解码消息

>>>
Word: "Mary Had a Little    Lamb"
Shift: 1

"Mary Had a Little    Lamb"
_Nbsz Ibe b Mjuumf    Mbnc_
Repeat? [y|n]: y

Word: _Nbsz Ibe b Mjuumf    Mbnc_
Shift: -1

_Nbsz Ibe b Mjuumf    Mbnc_
_Mary Had a Little    Lamb_
Repeat? [y|n]: n

>>>

答案 4 :(得分:0)

这是为Python 3编写的一个简单的Caesar密码程序,对于Python 2重写应该不是很困难:

import string

def main():
    key = 5
    table = str.maketrans(string.ascii_letters,
                          string.ascii_lowercase[key:] +
                          string.ascii_lowercase[:key] +
                          string.ascii_uppercase[key:] +
                          string.ascii_uppercase[:key])
    plaintext = input('Please enter a phrase: ')
    ciphertext = plaintext.translate(table)
    print('Your encrypted phrase is:', ciphertext)

if __name__ == '__main__':
    main()