首页 > 解决方案 > 改进加密算法

问题描述

最近我开始这个任务只是为了学校目的,但我最近决定我想继续这个作为一个新项目,并想就如何改进我的算法提出建议。我有一个想法,我希望每个字符更改加密密钥以使我的加密更安全,但我一直遇到困难,因为它无法解决,我无法解密我的最终加密文本

这是加密器:

text = input('Enter A Word : ') ##This asks a user for an input of text integers etc
encrypt = '' ##Empty Value used to store the encrypted value
temp = '' ##Empty temp value replaced at every iteration of the encryption process
temp2 =0 ##Empty temp value replaced at every iteration of the encryption process
temp_val=0
temp_char=''
rtext= text[::-1]
key=int(input('Enter your key (Your Encrypted Sentence Will Further be Encrypted Later) : '))##key used to shift the letters



for a in range (0,len(rtext)):
    if len(rtext) % 2==0:
        hlength=len(rtext)/2
    else:
        hlength=(len(rtext)+1)/2
print(hlength)
for i in range(int(hlength),len(rtext)):
    ##Rearranges text in a caps switch
    if str.islower(rtext[i])==True:
        temp=temp+str.upper(rtext[i])
    elif str.isupper(rtext[i])==True:
        temp=temp+str.lower(rtext[i])
    else:
        temp=temp+rtext[i]
for b in range(0,int(hlength)):
    ##Rearranges text in a caps switch
    if str.islower(rtext[b])==True:
        temp=temp+str.upper(rtext[b])
    elif str.isupper(rtext[b])==True:
        temp=temp+str.lower(rtext[b])
    else:
        temp=temp+rtext[b]
for j in range(0,len(temp)):
    temp_val=0
    temp2=0
    temp_val=ord(temp[j])
    temp2=temp2+temp_val+int(key)
    temp_char=temp_char+chr(temp2)
    encrypt=temp_char
print(encrypt)
print(temp)
print(temp2)

解密器:

text = input('Enter A Word : ') ##This asks a user for an input of text integers etc
decrypt = '' ##Empty Value used to store the encrypted value
order=0
characters=''
temp=''
rtext=text[::-1]

key=int(input('Enter your key (decryption) : '))##key used to shift the letters

for i in range (0,len(rtext)):
    order=0
    order=order+ord(rtext[i])-int(key)
    characters=characters+chr(order)
for a in range (0,len(rtext)):
    if len(rtext) % 2==0:
        hlength=len(rtext)/2
    else:
        hlength=(len(rtext)+1)/2
for j in range (int(hlength),len(characters)):
    if str.islower(characters[j])==True:
        temp=temp+str.upper(characters[j])
    elif str.isupper(characters[j])==True:
        temp=temp+str.lower(characters[j])
    else:
        temp=temp+characters[j]
for b in range (0,int(hlength)):
    if str.islower(characters[b])==True:
        temp=temp+str.upper(characters[b])
    elif str.isupper(characters[b])==True:
        temp=temp+str.lower(characters[b])
    else:
        temp=temp+characters[b]
print(temp)

我特别想更改变量键。

ord() - 将字符转换为等效的 Ascii chr() - 将 Ascii 数字转换为等效的字符 rtext - 获取用户输入的倒数

标签: pythonpython-3.xencryptionkey

解决方案


如果我们稍微简化加密器中的代码,我们会得到:

def encrypt_text(text: str, key: int):
    print("TEXT:", text, "KEY:", key)
    temp = ''
    temp2 = 0
    temp_val = 0
    temp_char = ''
    rtext = text[::-1]
    print("RTEXT:", rtext)

    hlength = len(rtext) // 2 + len(rtext) % 2   # half, round up
    print("HLENGTH:", hlength)

    for i in range(hlength, len(rtext)):
        # Rearrange text in a caps switch
        if rtext[i].islower():
            temp += rtext[i].upper()
        elif rtext[i].isupper():
            temp += rtext[i].lower()
        else:
            temp += rtext[i]

    print("TEMP:", temp)

    for b in range(0, int(hlength)):
        # Rearrange text in a caps switch
        if rtext[b].islower():
            temp += rtext[b].upper()
        elif rtext[b].isupper():
            temp += rtext[b].lower()
        else:
            temp += rtext[b]

    for j in range(len(temp)):
        temp_val = 0
        temp2 = 0
        temp_val = ord(temp[j])
        temp2 = temp2 + temp_val + int(key)
        temp_char = temp_char + chr(temp2)
        encrypt = temp_char

    print("ENCRYPT:", encrypt)
    print("TEMP:", temp)
    print("TEMP2:", temp2)
    return encrypt


text = "hello world"
key = 42
print("ENCRYPTED:", encrypt_text(text, key))

我将它放在一个函数中(并添加了一些打印语句),因此在开发时更容易使用。代码基本上和你的一样,除了

for a in range (0,len(rtext)):
    if len(rtext) % 2==0:
        hlength=len(rtext)/2
    else:
        hlength=(len(rtext)+1)/2

被替换为

hlength = len(rtext) // 2 + len(rtext) % 2   # half, round up

这给出了相同的结果(除了hlength是一个整数)。

您的前两个 for 循环执行相同的操作(在字符串上切换大小写)。我们可以为此编写一个函数:

def swap_case(str):
    res = ''
    for ch in str:
        if ch.islower():
            res += ch.upper()
        elif ch.isupper():
            res += ch.lower()
        else:
            res += ch
    return res

现在我们可以将前两个 for 循环替换为对我们函数的调用:

temp += swap_case(rtext[hlength:len(rtext)])  # or shorter rtext[hlength:]
temp += swap_case(rtext[0:hlength])           # or shorter rtext[:hlength]

它只是碰巧.swapcase()已经是一个字符串方法,所以我们真的不需要我们的 swap_case 函数,可以写:

temp += rtext[hlength:].swapcase()
temp += rtext[:hlength].swapcase()

您的第三个 for 循环:

for j in range(len(temp)):
    temp_val = 0                          # this value is not used (it's overwritten 2 lines down)
    temp2 = 0
    temp_val = ord(temp[j])              
    temp2 = temp2 + temp_val + int(key)   # temp2 is always zero at this point
    temp_char = temp_char + chr(temp2)
    encrypt = temp_char

可以简化为(temp_char上面的初始值设置为空字符串):

for j in range(len(temp)):       # for each index position (j)
    temp_val = ord(temp[j])      # use the character at from temp at index j
    temp2 = temp_val + int(key)  # key is already an int from your: key=int(input('Enter your key (decryption) : '))
    temp_char += chr(temp2)
    encrypt = temp_char          # hmm... just overwriting encrypt on every iteration

评论意味着它可能更简单:

encrypt = ''
for character in temp:
    temp_val = ord(character)
    temp2 = temp_val + key
    encrypt += chr(temp2) 

这给我们留下了(评论列举了所采取的步骤):

def encrypt_text(text: str, key: int):
    temp = ''
    rtext = text[::-1]                           # (1) reverse the string

    hlength = len(rtext) // 2 + len(rtext) % 2   # (2) split the string on hlength
    second_part = rtext[hlength:].swapcase()     #  .. and swap case on the parts
    first_part = rtext[:hlength].swapcase()
    temp += second_part                          # (3) and put the second part..
    temp += first_part                           # ..  before the first part

    encrypt = ''
    for character in temp:
        temp_val = ord(character)
        temp2 = temp_val + key                   # (4) add key to every character
        encrypt += chr(temp2) 

    return encrypt

要解密使用此函数加密的字符串,我们需要执行“反向和反向”操作:

def decrypt_text(encrypted, key):
    temp = ''
    for ch in encrypted:
        temp += chr(ord(ch) - key)   # subtract key from every character (4)

    hlength = len(encrypted) // 2 + len(encrypted) % 2
    half = len(encrypted) - hlength  # the split point is a mirror image of what it is in encrypt_text (3)

    rtext = ''
    rtext += temp[half:].swapcase()  # re-assemble the string and swap case (2)
    rtext += temp[:half].swapcase()

    text = rtext[::-1]               # finally reverse (1)
    return text

推荐阅读