Search code examples
pythonencryptionmodular-arithmetic

Understanding modular arithmetic in encryption example


I understand modular arithmetic in its basic mathematical form for example:

38 = 2 mod 12

However in the following encryption and decryption code example it is used along with other math and I don't understand what it is used for.

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)

Can someone explain it to me please?


Solution

  • in the parts key_c = ord(key[i % len(key)])

    The % is used to avoid an IndexError - it just wraps the key around the message when the key is shorter than the message.

    In encryped.append(chr((msg_c + key_c) % 127))

    The % is used to keep the resulting chr in the 7-bit ascii range.

    Think about % here like the clock: when it's x hours later than y 'o clock, it's (x+y) % 12 'o clock.

    On a side note: I think it must be obvious, I want to mention it nonetheless: this "cipher" is of course far away from being secure.