加密大写字母 python vigenere

encrypting upper-case letters python vigenere

我在加密大写字母时遇到问题,例如如果消息是 COMPUTING IS FUN 关键字是 GCSE 我应该得到 JRFUBWBSN LL KBQ 但我的实际结果是 xftipkpgb zz ype。这个结果既没有正确的字母也不是大写。任何帮助表示赞赏

                    message = input('\nenter message: ')
                    keyword = input('enter keyword: ')
                    def chr_to_inta(char):
                        return 0 if char == 'Z' else ord(char)-64
                    def int_to_chra(integer):
                        return 'Z' if integer == 0 else chr(integer+64)
                    def add_charsa(msg, key):
                        return int_to_chr(( chr_to_int(msg) + chr_to_int(key)) % 26 )


                    def chr_to_int(char):
                        return 0 if char == 'z' else ord(char)-96
                    def int_to_chr(integer):
                        return 'z' if integer == 0 else chr(integer+96)
                    def add_chars(msg, key):
                        return int_to_chr(( chr_to_int(msg) + chr_to_int(key)) % 26 )

                    def vigenere(message, keyword):

                        keystream = cycle(keyword)
                        new = ''
                        for msg in message:
                            if msg == ' ': # adds a space
                                new += ' '
                            elif 96 < ord(msg) < 123: # if lowercase
                                new += add_chars(msg, next(keystream))

                            else: # if uppercase
                                new += add_charsa(msg, next(keystream))

                        return new

                    new = vigenere(message, keyword)
                    print('your encrypted message is: ',new)

因为你似乎不明白我在说什么:

def add_charsa(msg, key):
    return int_to_chr(( chr_to_int(msg) + chr_to_int(key)) % 26 )

是您目前拥有的。有了这个,你会得到错误的输出:

>>> vigenere('COMPUTING IS FUN','GCSE')
'xftipkpgb zz ype'

这是因为您没有更改此函数的 return 语句来调用新的大写函数。如果将 return 语句更改为:

def add_charsa(msg, key):
    return int_to_chra(( chr_to_inta(msg) + chr_to_inta(key)) % 26 )
#notice the change in function calls from int_to_chr -> int_to_chra, and chr_to_int -> chr_to_inta

您将得到预期的结果:

>>> vigenere('COMPUTING IS FUN','GCSE')
'JRFUBWBSN LL KBQ'

值得一提的是,如果您的密钥混合了大小写字母,这将不起作用。很好。我会改为将您的 keystream 更改为:keystream = cycle(keyword.lower()) 那么您的函数将是:

def add_charsa(msg, key):
        return int_to_chra(( chr_to_inta(msg) + chr_to_int(key)) % 26 )
    #notice the call to chr_to_int(key) because key will always be lower case