自定义Python加密算法

Jac*_*nta 1 python encryption

嘿,我一直在研究这个问题,我可以记得我哥哥让我通过这个同样的算法.

基本上,它只是添加了键和短语中两个字符的ascii值.

我可以加密它:

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
Run Code Online (Sandbox Code Playgroud)

但我似乎无法记住我们在解密方面所做的工作.它很难逆转一个mod:P有什么想法吗?

Fan*_*Lin 10

这很简单,让我们看看它是如何工作的.首先,通过减去密钥获得加密的消息.

enc = msg + key (mod 127)
Run Code Online (Sandbox Code Playgroud)

我们怎样才能获得原始信息?这很容易,双方减去关键

enc - key = msg + key - key (mod 127)
Run Code Online (Sandbox Code Playgroud)

在这里,我们得到:

enc - key = msg (mod 127)
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅模块化算术,我认为它应该属于组/字段/环之一.我不是数学专家,对于更深入的理论知识,你可以在数论中找到它们.这是精炼的代码:

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)
Run Code Online (Sandbox Code Playgroud)

产量

Message: 'Hello world'
Key: 'This_is_my_awsome_secret_key'
Encrypted: '\x1dNV`O\nkO`fD'
Decrypted: 'Hello world'
Run Code Online (Sandbox Code Playgroud)