【发布时间】:2020-02-25 05:42:08
【问题描述】:
这是我在 stackoverflow 上发布的第一个问题,感谢任何和所有帮助/批评/帮助...我需要我能得到的所有帮助,哈哈。
我对编程很陌生。
目的是创建一个凯撒密码,对用户输入的字符串进行加密和解密,添加用户输入offset_value,然后将其改回字符。
我使用的是 ASCII 字符。问题是我需要将加密和解密隔离为 ASCII 32 ('a') - ASCII 126 ('~')。我不确定如何创建一个循环返回 94 个字符的函数。
因此,例如,如果 char 是 'Z',即 ASCII ord 94,如果我们添加用户输入 offset_value,这可能是 90,这将使 ord 184。超出范围。
这导致了真正的问题,即暴力加密。它工作......有点。它需要显示所有可能的结果,offset_value 在 1 和 94 之间变化。例如,如果我们用 x 的offset_value(x 是 1-94 之间的任何数字)解密每个字母会发生什么。
相反,它只是不断上升。
这些有意义吗?
我的代码如下。我知道我还没有创建任何函数,但我会的。
提前谢谢各位。
choice = 0
list1 = [1, 2, 3, 4]
list2 = list(range(1, 95))
new_ord = 0
index = 1
encryption = ''
decryption = ''
offset_value = 1
#while loop allows for multiple use, option 4 ends loop
while choice != 4:
print('*** Menu ***')
print('\r')
print('1. Encrypt string')
print('2. Decrypt string')
print('3. Brute force decryption')
print('4. Quit')
print('\r')
choice = int(input('What would you like to do [1,2,3,4]? '))
#invalid user input loop, valid entry ends loop
while choice not in list1:
print('\r')
print('Invalid choice, please enter either 1, 2, 3 or 4.')
print('\r')
choice = int(input('What would you like to do [1,2,3,4]? '))
#user chooses 'encrypt string', stores data
if choice == 1:
print('\r')
string_to_encrypt = str(input('Please enter string to encrypt: '))
offset_value = int(input('Please enter offset value (1 to 94): '))
#invalid user input loop, valid entry ends loop
while offset_value not in list2:
offset_value = int(input('Please enter offset value (1 to 94): '))
#encryption loop for length of string_to_encrypt
for letter in string_to_encrypt:
encryption = encryption + chr((ord(letter) + offset_value))
#prints encrypted string
print('\r')
print('Encrypted string:')
print(encryption)
print('\r')
#clears ecryption data
encryption = ''
#user chooses 'decrypt string', stores data
elif choice == 2:
print('\r')
string_to_decrypt = str(input('Please enter string to decrypt: '))
offset_value = int(input('Please enter offset value (1 to 94): '))
#invalid user input loop, valid entry ends loop
while offset_value not in list2:
offset_value = int(input('Please enter offset value (1 to 94): '))
#decryption loop for length of string_to_decrypt
for letter in string_to_decrypt:
decryption = decryption + chr((ord(letter) - offset_value))
#prints decrypted string
print('\r')
print('Decrypted string:')
print(decryption)
print('\r')
#clears decryption data
decryption = ''
#user chooses 'Brute Force Decryption
elif choice == 3:
string_to_decrypt = str(input('Please enter string to decrypt: '))
for number in range(94):
for letter in string_to_decrypt:
decryption = decryption + chr((ord(letter) - offset_value))
print('Offset: ', index, '= Decrypted String: ', decryption)
offset_value = offset_value + 1
index = index + 1
decryption = ''
#user chooses 'quit'
print('Goodbye.')
【问题讨论】:
-
ascii 表上的 32 映射到一个空格(''),而不是 'a'(即 97)。此外,该字符范围有 95 个字符,而不是 94 个(假设 126 包括在内)。
标签: python python-3.x encryption ascii caesar-cipher