加密/解密 - Python GCSE

时间:2016-02-23 08:10:13

标签: python encryption

我目前正在尝试为学校编写一个程序,以加密和解密输入的消息。我需要加密或解密的消息只在字母表中没有其他符号或键,例如,输入的偏移量为5使用消息面包加密,我希望它输出' afs'。有人可以帮忙吗?这是我目前的代码:

def find_offset():

    offset = int(input("Enter an offset: "))

    if offset > 25 or offset < 0:
        print("Invalid offset, please enter another offset: ")
        find_offset()
    else:
        print("Okay")
        encrypt_fun(offset)


def encrypt_fun(offset):

    choice = ''
    while choice != '3':
        choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, 3 to Exit Program: ")
        if choice == '1':
            message = input("\nEnter the message to encrypt: ")

            for i in range(0, len(message)):
                result = chr(ord(message[i]) + offset)
                print(result, end=''),

        elif choice == '2':
            message = input("\nEnter the message to decrypt: ")

            for i in range(0, len(message)):
                result = chr(ord(message[i]) - offset)
                print(result, end=''),

        elif choice != '3':
            print("You have entered an invalid choice. Please try again.\n\n")

find_offset()

1 个答案:

答案 0 :(得分:0)

目前,如果您超过或低于a (97)z (122)的序数值,则不会检查任何界限。

如果您要指定这些条件,并检查添加或减去偏移量的时间,您会找到您要查找的结果。

LOWER_BOUND = 97
UPPER_BOUND = 122

def alter_char(char, offset):
    """
    Alter char will take a character as input, change the ordinal value as 
    per the offset supplied, and then perform some bounds checks to ensure
    it is still within the `a <-> z` ordinal range. If the value exceeds
    the range, it will wrap-around to ensure only alphabetic characters
    are used.

    :param str char: The character you wish to manipulate
    :param int offset: The offset with which to alter the character
    :return: Returns the altered character
    :rtype: str
    """
    char_ord = ord(char) + offset
    if char_ord > UPPER_BOUND:
        return chr(LOWER_BOUND + (char_ord - UPPER_BOUND) - 1)
    if char_ord < LOWER_BOUND:
        return chr(UPPER_BOUND - (LOWER_BOUND - char_ord) + 1)
    return chr(char_ord)

有了这些内容,您可以更改result = chr(ord(message[i]) + offset)行以调用alter_char函数来确定您正在寻找的字符,即

result = alter_char(message[i], offset)  # for encryption
result = alter_char(message[i], -offset) # for decryption
# Prefixing the offset with a `-` is functionally equivalent to multiplying
# the offset by `-1`

顺便说一句,字符串是自然可迭代的,因此您的for i in range循环可以重构为

for char in message:
    result = alter_char(char, offset)

或更进一步将其转变为列表理解

result = ''.join([alter_char(char, offset) for char in message])

请注意,这仍然只能满足提交加密和解密的小写邮件的要求,因为大写字母的序数值不同。