How could I make my decryption program recognize which character the encrypted character belongs to, if each character could have 3 possible answers?

huangapple go评论132阅读模式
英文:

How could I make my decryption program recognize which character the encrypted character belongs to, if each character could have 3 possible answers?

问题

在代码的解密部分,您面临的问题是字符在列表中可能重复的情况,例如字符 "&" 可能出现在多个字符的列表中,如 a = [&, T, 4],b = [%, &, 2] 和 c = [G, 1, &]。您想知道如何让程序识别哪个字符是所需的,如果 "ab" 加密后变成 "&2",如何编写代码以理解 "&" 是代表 "a" 而不是 "b" 和 "c",以避免返回 "cbb" 而不是 "ab"。

您提到的将信号代码放在每个字符列表的末尾的方法是一个不错的思路。您可以尝试以下方法来实现这一点:

  1. 为每个字符的列表添加一个唯一的信号代码,以标识哪个字符被加密。例如:

    a = [&, T, 4, 1]
    b = [%, &, 2, 2]
    c = [G, 1, &, 3]
    

    在上面的示例中,信号代码是列表的最后一个元素。

  2. 在加密时,将信号代码添加到加密字符串的末尾,以指示加密的字符。例如,如果加密 "ab",则加密后的字符串可能是 "&24"。

  3. 在解密时,从加密字符串的末尾提取信号代码,并使用它来确定要解密的字符。根据信号代码查找对应的字符列表,然后将加密字符串分割为相应的部分,并将其解密为原始字符。

这种方法可以解决字符重复的问题,因为信号代码唯一标识了加密字符的来源。您可以在解密过程中使用信号代码来准确地还原原始字符,而不会混淆它们。

英文:

For clarification, this is an assignment from a class, it's not supposed to be a fully functioning and useful encryption.

Heyo, I've had an assignment where I need to write an encryption program that gives each character three possible characters that it would turn into when encrypted. For example: a = [#, S, 2], b = [&, =, @]

import string
import random
import json

question = input("Would you like to Encrypt or Decrypt a string?\n")

if question == "Encrypt":

    # We choose our random characters from encryptionList, and also create the dictionary from the same string using dict.fromkeys().
    encryptionList = string.ascii_letters + string.digits + string.punctuation + " "
    dictionary1 = dict.fromkeys(encryptionList, )
    dictionary2 = dict.fromkeys(encryptionList, )

    # Adding the three random characters to our Dictionary by random, while loop checks whether each index is similar, and chooses another one if it is.
    for key in dictionary1:
        listOfLetters1 = list()
        listOfLetters2 = list()

        for i in range(3):
            listOfLetters1.append(random.choice(encryptionList))

        for i in range(3):
            listOfLetters2.append(random.choice(encryptionList))

        for j in range(3):
            while (listOfLetters1[j] == listOfLetters2[j]):
                listOfLetters1[j] = random.choice(encryptionList)

        dictionary1[key] = listOfLetters1
        dictionary2[key] = listOfLetters2
        

    # Asking for the string.
    toEncrypt = input("Please enter a string to ecrypt:\n")
    methodEncrypt = input("Which encryption method would you like? (1, 2)\n")

    # Creating the encrypted message.
    randomLetter = list()
    if methodEncrypt == "1":
        encryptedString = ""
        for letter in toEncrypt:
            dictLetter = dictionary1[letter]
            randomLetter.append(random.choice(dictLetter))
        key1 = open("Key1.txt", "w")
        key1.write(json.dumps(dictionary1))

    if methodEncrypt == "2":
        encryptedString = ""
        for letter in toEncrypt:
            dictLetter = dictionary2[letter]
            randomLetter.append(random.choice(dictLetter))
        key2 = open("Key2.txt", "w")
        key2.write(json.dumps(dictionary2))

    # Using str(e) for e in randomLetter to swap everything inside the list into a string. ''.join() will join the elements of the list together.
    encryptedMessage = ''.join(str(e) for e in randomLetter)
    if methodEncrypt == "1":
        print(f"Your encrypted message is now: {encryptedMessage}\nYour key is 'Key1'\nTo decrypt your message you will need this information.")
    elif methodEncrypt == "2":
        print(f"Your encrypted message is now: {encryptedMessage}\nYour key is 'Key2'\nTo decrypt your message you will need this information.")

elif question == "Decrypt":
    # Asking for the string.
    toDecrypt = input("Please enter a string to decrypt:\n")
    methodDecrypt = input("Which method did you use to encrypt the string with? (1, 2)\n")
    
    # Decrypting the message.
    keyFile = input("Please enter the name of your Key:\n")
    decryptKey = open(keyFile, "r")
    decryptFile = decryptKey.read()
    print(decryptFile)
    decryptDict = json.loads(decryptFile)
    decryptedString = ""

    for letter in toDecrypt:
        for char in decryptDict:
            charList = decryptDict[char]
            if letter in charList:
                decryptedString += char

    print(f"Your decrypted message is now: {decryptedString}\n")

My problem arises in the decryption portion of the code. Since the characters inside the lists could be repeated, for example the character "&" could be in two or more characters: a = [&, T, 4] and b = [%, &, 2] and c = [G, 1, &]
How could I make it so the program can detect which one of these is the actual character we need, if ab turns into &2, how could I code it so it'd understand that the & is for a and not b and c, and not return cbb instead of ab as a result?

I was thinking of putting a signal code at the end of each character list, such as 1, 2, 3, 4, etc... and if that was the encrypted character it would add the signal code to the encrypted string as well (a = [&, T, 4, 1], if a were to be encrypted it would add 1 to the end of the encrypted string, and it would be later decoded from that signal code, but since numbers and all other characters could also be inside of the string that the user would like to encrypt, it would not work.

答案1

得分: 0

根据你的观察,如果加密时有多个字符被替换成相同的字符,那么解密将没有办法进行。为了使这种加密方法有效,你需要确保每个输出字符最多用于加密一个输入字符。

请注意,这意味着你需要至少有三倍多的输出字符数量,与输入字符数量相比,例如,你可以使用所有可打印字符来加密字符 a-z。如果这是一个问题,你可以通过用两个输出字符的字符串加密每个输入字符来解决这个问题。例如,加密字符 "a" 的选项可以是 "cw"、"pl" 和 "qr"。哪一个是更好的解决方案取决于具体的分配方式。

如果我理解 "信号代码" 的概念,这可能不是一个好的方法。如果你为每个输入字符分配一个单独的信号代码,请注意,只使用信号代码就可以解密文本,根本不需要加密文本。


顺便说一下,我查看了你的代码并有一些注意事项。代码存在一些问题,主要是因为它过于复杂化,是意大利面代码的一个例子。

如果将逻辑部分(加密、解密等)转化为函数,代码将变得更容易理解。另外,将输入和输出与程序逻辑分离是一个良好的实践。更好的程序结构可能是:

# 导入模块
...

# 用于构建用于加密的字典的函数
def build_encryption_dictionary():
    ...
    return enc_dict

# 使用加密字典加密字符串的函数
def encrypt(in_string, enc_dict):
    ...
    return encrypted

# 使用加密字典解密加密字符串的函数
def decrypt(encrypted_string, enc_dict):
    ...
    return decrypted

enc_dict = build_encryption_dictionary()

# 询问用户想要执行什么操作
...

# 使用上述函数并打印结果
...
英文:

As you observed, if more than one character is substituted by the same character by the encryption, there is no way to perform decryption. For this encryption method to work, you need to ensure that every output character is used to encrypt at most one input character.

Note that this means that you need at least three time as many output characters as you have input characters, e.g., you can encrypt characters a-z using all printable characters. If this is a problem, you can work around this by encrypting every input character by a string of two output characters. For example, the options for encrypting the character "a" could be "cw", "pl" and "qr". It depends on the exact assignment which one of these is a better solution.

If I understand the "signal code" idea, this is probably not a good way to go. If you assign a single signal code to every input character, note that it would be possible to decrypt the text only using the signal codes and you would not need the encrypted text at all.


As a sidenote, I had a look at your code and I have a few notes. The code has several issues, that mostly boil down to it being overcomplicated and an example of spaghetti code.

It will make the code easier to understand if you turn logical parts (encryption, decryption, ...) into functions. Also, it is a good practice to separate input and output from the program logic. A better way to structure the program would be

# Imports
...

# Function for building the dictionary used for encryption
def build_encryption_dictionary():
    ...
    return enc_dict


# Function to encrypt a string using an encryption dictionary
def encrypt(in_string, enc_dict):
    ...
    return encrypted


# Function to decrypt an encrypted string using an encryption dictionary
def decrypt(encrypted_string, enc_dict):
    ...
    return decrypted


enc_dict = build_encryption_dictionary()

# Ask the user what they want to do
...

# Use the above functions and print the result
...

</details>



huangapple
  • 本文由 发表于 2023年8月11日 04:08:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76879005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定