Custom Python Encryption algorithm

17,581

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

enc = msg + key (mod 127)

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

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

And here we get:

enc - key = msg (mod 127)

For more details, please refer to Modular arithmetic, I think it should belong one of group/field/ring. I'm not an expert in math, for further reading, you should check out 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'
Share:
17,581

Related videos on Youtube

Jacob Valenta
Author by

Jacob Valenta

Python (Django) and AngularJS Web Developer

Updated on June 04, 2022

Comments

  • Jacob Valenta
    Jacob Valenta almost 2 years

    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?

  • Jacob Valenta
    Jacob Valenta about 13 years
    Would I be able to make the encrypted file only ascii printable chars if I were to do: chr((key_c + string_c) % 95 + 32)
  • Tejas Patel
    Tejas Patel over 3 years
    Its a good one. Osam dude.. Thanks for saving my day

Related