【发布时间】:2015-09-23 11:06:20
【问题描述】:
我一直在尝试将这个php函数改成python,但无济于事。
public static function encode($text, $KEY) {
$pkcs5text= self::pkcs5_pad($text,16);
$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($size, MCRYPT_RAND);
$bin = pack('H*', bin2hex($pkcs5text) );
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $KEY, $bin, MCRYPT_MODE_ECB, $iv);
return base64_encode($encrypted);
}
我的 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
两个脚本都从彼此不同的同一消息生成编码文本。我不确定我哪里出错了。如何在 rijndael 128 之上将 mcrypt 实现到 python 中?
【问题讨论】:
-
我尝试了你的代码,但它给了我错误“AttributeError: module 'rijndael' has no attribute 'rijndael'” 这是为“rijndael.rijndael(padded_key, BLOCK_SIZE)”行给出的错误
标签: php python aes mcrypt rijndael