2

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?

3 Answers 3

15

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'
Sign up to request clarification or add additional context in comments.

2 Comments

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)
Its a good one. Osam dude.. Thanks for saving my day
2

Decryption is the same, except with minus instead of plus.

Comments

0

But you do not need to inverse the mod, just the + key_c, right? So just add 128, subtract key_c, and do modulo 127 again to keep in range. (instead of the last line, all the other lines are the same as with encrypting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.