[Python] How to encrypt my sentence using string libraray [closed]

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    My encryption/decryption program does not correctly decrypt sentences it has encrypted. As an example, when I encrypt the string I am amirreza, the encrypted output is ! Hx HxsLLxsH and the key is 13. Then, when I supply ! Hx HxsLLxsH with my key 13 to my program to be decrypted, the result is - 'm 'mz88mz', which is incorrect. I am unable to find the bug in the program.

    import random
    import string

    while True:
    print("What do you want to do? \n \t1) str to code \n \t2) code to str \n \t3) exit")
    answer = input("Tell me your answer:")

    if answer == "1":
    sentense = input("What sentence do you want to be coded?")
    list_sentense = list(sentense)
    l1 = list(string.ascii_letters + string.digits + string.punctuation)
    l2 = []

    random.seed(len(list_sentense)) # Set seed based on sentence length

    # Filling l2 with random characters
    for i in range(0, len(l1)):
    l2.append(random.choice(l1))

    dict1 = dict(zip(l1, l2)) # Create the dictionary for encoding

    # Encoding
    for i in range(0, len(list_sentense)):
    if list_sentense in dict1:
    list_sentense = dict1[list_sentense]

    encrypted_message = ''.join(list_sentense)
    print("Encrypted message:", encrypted_message)
    print(f"Your key to unlock the code is {len(list_sentense)}")
    break

    elif answer == "2":
    input_coded_sentence = input("What is your coded sentence?")
    key = int(input("What is your key to break the code?"))
    list_input = list(input_coded_sentence)

    l1 = list(string.ascii_letters + string.digits + string.punctuation)
    l2 = []

    random.seed(key) # Use the same seed for decoding


    for i in range(0, len(l1)):
    l2.append(random.choice(l1))

    dict2 = dict(zip(l2, l1)) # Reverse dictionary for decoding

    # Decoding
    for i in range(0, len(list_input)):
    if list_input in dict2: # Check if character exists in dict2
    list_input = dict2[list_input]

    decrypted_message = ''.join(list_input)
    print("Decrypted message:", decrypted_message)
    break

    elif answer == "3":
    print("Goodbye!")
    break

    else:
    print("What are you doing?")

    Continue reading...

Compartilhe esta Página