Jacob Valenta Jacob Valenta - 1 month ago 11
Python Question

Custom Python Encryption algorithm

Hey, I have been working on this for a while, and I can remebr my brother stepped me through this very same alogorithm.

Basicly, it just adds the ascii values of both the characters from the key, and the phrase.

I can encrypt it with this:

def encrypt(key, string):
encoded = ''
for i in range(len(string)):
key_c = ord(key[i % len(key)])
string_c = ord(string[i % len(string)])
encoded += chr((key_c + string_c) % 127)
return encoded


But I can't seem to remember what we did as far as decrypting. Its difficult to revers a mod :P
Any ideas?

Answer

That's simple, let's see how it works. First of all, the encrypted message is obtained by subtracting key.

enc = msg + key (mod 127)

How can we obtain the original message? That's easy, subtract key in both side

enc - key = msg + key - key (mod 127)

And here we get:

enc - key = msg (mod 127)

For more details, please reference to Modular arithmetic, I think it should belong one of group/field/ring. I'm not expert in math, for deeper theoretical knowledge, you can found them in Number theory. Here is the refined code:

def encrypt(key, msg):
    encryped = []
    for i, c in enumerate(msg):
        key_c = ord(key[i % len(key)])
        msg_c = ord(c)
        encryped.append(chr((msg_c + key_c) % 127))
    return ''.join(encryped)

def decrypt(key, encryped):
    msg = []
    for i, c in enumerate(encryped):
        key_c = ord(key[i % len(key)])
        enc_c = ord(c)
        msg.append(chr((enc_c - key_c) % 127))
    return ''.join(msg)

if __name__ == '__main__':
    key = 'This_is_my_awsome_secret_key'
    msg = 'Hello world'
    encrypted = encrypt(key, msg)
    decrypted = decrypt(key, encrypted)

    print 'Message:', repr(msg)
    print 'Key:', repr(key)
    print 'Encrypted:', repr(encrypted)
    print 'Decrypted:', repr(decrypted)

Output

Message: 'Hello world'
Key: 'This_is_my_awsome_secret_key'
Encrypted: '\x1dNV`O\nkO`fD'
Decrypted: 'Hello world'