解密Python中使用PHP中的MCRYPT_RIJNDAEL_256加密的字符串

dha*_*esh 13 php python encryption mcrypt

我有一个PHP函数加密文本如下:

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

    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $Key, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
Run Code Online (Sandbox Code Playgroud)

如何在Python中解密这些值?

101*_*100 16

要解密这种加密形式,您需要获得Rijndael的版本.一个可以在这里找到.然后,您将需要模拟PHP Mcrypt模块中使用的键和文本填充.他们添加'\0'填充文本并键入正确的大小.它们使用的是256位块大小,并且您使用的密钥使用的密钥大小为128(如果您给它一个更大的密钥,它可能会增加).不幸的是,我链接的Python实现一次只编码一个块.我创建了python函数,用于模拟Python中的加密(用于测试)和解密

import rijndael
import base64

KEY_SIZE = 16
BLOCK_SIZE = 32

def encrypt(key, plaintext):
    padded_key = key.ljust(KEY_SIZE, '\0')
    padded_text = plaintext + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE) * '\0'

    # could also be one of
    #if len(plaintext) % BLOCK_SIZE != 0:
    #    padded_text = plaintext.ljust((len(plaintext) / BLOCK_SIZE) + 1 * BLOCKSIZE), '\0')
    # -OR-
    #padded_text = plaintext.ljust((len(plaintext) + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE)), '\0')

    r = rijndael.rijndael(padded_key, BLOCK_SIZE)

    ciphertext = ''
    for start in range(0, len(padded_text), BLOCK_SIZE):
        ciphertext += r.encrypt(padded_text[start:start+BLOCK_SIZE])

    encoded = base64.b64encode(ciphertext)

    return encoded


def decrypt(key, encoded):
    padded_key = key.ljust(KEY_SIZE, '\0')

    ciphertext = base64.b64decode(encoded)

    r = rijndael.rijndael(padded_key, BLOCK_SIZE)

    padded_text = ''
    for start in range(0, len(ciphertext), BLOCK_SIZE):
        padded_text += r.decrypt(ciphertext[start:start+BLOCK_SIZE])

    plaintext = padded_text.split('\x00', 1)[0]

    return plaintext
Run Code Online (Sandbox Code Playgroud)

这可以使用如下:

key = 'MyKey'
text = 'test'

encoded = encrypt(key, text)
print repr(encoded)
# prints 'I+KlvwIK2e690lPLDQMMUf5kfZmdZRIexYJp1SLWRJY='

decoded = decrypt(key, encoded)
print repr(decoded)
# prints 'test'
Run Code Online (Sandbox Code Playgroud)

为了比较,这里是PHP的输出,具有相同的文本:

$ php -a
Interactive shell

php > $key = 'MyKey';
php > $text = 'test';
php > $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB);
php > $encoded = base64_encode($output);
php > echo $encoded;
I+KlvwIK2e690lPLDQMMUf5kfZmdZRIexYJp1SLWRJY=
Run Code Online (Sandbox Code Playgroud)

  • @ 101100使用"pip install rijndael"安装包但出错.r = rijndael.rijndael(padded_key,BLOCK_SIZE)AttributeError:'module'对象没有属性'rijndael' (2认同)