Home > database >  Basic Encryption, by manipulating ASCII values to create an encryption
Basic Encryption, by manipulating ASCII values to create an encryption

Time:12-29

The most basic encryption method is to map a char to another char by a certain math rule. Because every char has an ASCII value, we can manipulate this value with a simple math expression. For example 'a' 1 would give us 'b', because 'a' value is 97 and 'b' value is 98.

You will need to write a method which does exactly that - get a string as text and an int as the rule of manipulation, and should return encrypted text. for example:

encrypt("a",1) = "b"

If the value exceeds 255, it should 'wrap'. ie. if the value is 345 it should wrap to 89.

def encrypt(text, rule):
    asc_list = []
    asc_enc = []
    for i in text:
        asc_list.append(ord(i))
    for j in asc_list:
        while j > 0:
            j  = rule
        if j <= 255 and j >= 0:
            asc_enc.append(chr(j))
        else:
            asc_enc.append(chr(j-256))
    return " ".join(asc_enc)

i wanted to find a more optimized version of my code, in order to learn a more efficient way

CodePudding user response:

If I understand you correctly you want to use modulo operator (%):

def encrypt(text, rule):
    return "".join(chr((ord(ch)   rule) % 256) for ch in text)


print(encrypt("abcxyz", 1))

Prints:

bcdyz{
  • Related