Don
Don

Reputation: 3

How to have the decryption function of this encryption function in python

If this is an encryption function:

(ascii_value % a_ big_ prime_number + a_number_of_ user’s_choice)

what would be the opposite decrypt function to convert the encrypted string into the original one and how to implement it in python.

Encrypt function will be like :

def encrypt_function(string):

    encrypted_string = ''
    user_input = int(input('Enter an integer'))

    for c in string:
        encrypted_string += chr((ord(c) % 173 + user_input))

    return encrypted_string

encrypt_function('hello')

the output will be something like 'þûĂĂą' with user_input = 150, how to create a method that returns the original string 'hello' and works with different prime numbers other than 173.

Upvotes: 0

Views: 59

Answers (2)

Florian Weimer
Florian Weimer

Reputation: 33694

If ascii_value is just a number between 0 and 127 (as the name ascii_value implies), you can just subtract user_input and get back the original value, assuming that user_input is larger than 127.

This works because if a < n (and both numbers are positive), then a % n always equals a. On the other hand, if n is not large enough, then there is irretrievable information loss. In short, this is a very poor encryption scheme.

Upvotes: 0

Tom Riddle
Tom Riddle

Reputation: 93

Code is not indented properly. I believe correct code should be something like this :

def encrypt_function(string):

    encrypted_string = ''
    user_input = int(input('Enter an integer'))

    for c in string:
        encrypted_string += chr((ord(c) % 173 + user_input))

    return encrypted_string

Pointing flaws in code :

  1. ord(c) outputs an integer in range(0,255). So if you are using ord(c)%173 as shown in the code you will have many to one mapping and it won't be possible to decrypt (because in the example you mentioned A(its ord is 0x41(65 in base 10) and 0xee(238 in base 10)). It can be brute forced i.e. check all possible values but this can get tricky if the length of your string is 10 and assume each has 2(this will be based on prime you choose) mappings so you might have to check 2^10 combinations).

  2. In the line encrypted_string += chr((ord(c) % 173 + user_input)) you are adding ord(c)%173 to an integer which is entered by user. There are chances that the value ord(c) % 173 + user_input might go beyond 255(the range of chr() function is (0,255) inclusive)

Refer to documentation for more details:

ord() can be found here and chr() van be found here

Upvotes: 1

Related Questions