Decrypting strings in Python that were encrypted with MCRYPT_RIJNDAEL_256 in PHP

后端 未结 3 671
失恋的感觉
失恋的感觉 2020-11-30 08:48

I have a function in PHP that encrypts text as follows:

function encrypt($text)
{
    $Key = \"MyKey\";

    return trim(base64_encode(mcrypt_encrypt(MCRYPT_         


        
3条回答
  •  没有蜡笔的小新
    2020-11-30 09:49

    Although the answer from @101100 was a good one at the time, it's no longer viable. The reference is now a broken link, and the code would only run on older Pythons (<3).

    Instead, the pprp project seems to fill the void nicely. On Python 2 or Python 3, just pip install pprp, then:

    import pprp
    import base64
    
    KEY_SIZE = 16
    BLOCK_SIZE = 32
    
    
    def encrypt(key, plaintext):
        key = key.encode('ascii')
        plaintext = plaintext.encode('utf-8')
        padded_key = key.ljust(KEY_SIZE, b'\0')
    
        sg = pprp.data_source_gen(plaintext, block_size=BLOCK_SIZE)
        eg = pprp.rjindael_encrypt_gen(padded_key, sg, block_size=BLOCK_SIZE)
    
        ciphertext = pprp.encrypt_sink(eg)
    
        encoded = base64.b64encode(ciphertext)
    
        return encoded.decode('ascii')
    
    
    def decrypt(key, encoded):
        key = key.encode('ascii')
        padded_key = key.ljust(KEY_SIZE, b'\0')
    
        ciphertext = base64.b64decode(encoded.encode('ascii'))
    
        sg = pprp.data_source_gen(ciphertext, block_size=BLOCK_SIZE)
        dg = pprp.rjindael_decrypt_gen(padded_key, sg, block_size=BLOCK_SIZE)
    
        return pprp.decrypt_sink(dg).decode('utf-8')
    
    
    key = 'MyKey'
    text = 'test'
    
    encoded = encrypt(key, text)
    print(repr(encoded))
    # prints 'ju0pt5Y63Vj4qiViL4VL83Wjgirq4QsGDkj+tDcNcrw='
    
    decoded = decrypt(key, encoded)
    print(repr(decoded))
    # prints 'test'
    

    I'm a little dismayed that the ciphertext comes out different than what you see with 101100's answer. I have, however, used this technique to successfully decrypt data encrypted in PHP as described in the OP.

提交回复
热议问题