开发者

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 开发者_C百科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?


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'


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜