繁体   English   中英

为什么用php编写的河豚代码在Python中给出不同的结果?

[英]Why does blowfish code written in php give different results in Python?

我对加密不是很熟练,我一直在使用我下面提到的 php 代码进行加密。 现在我想用 python 编写相同的代码,但我找不到解决方案。

<?PHP
  $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  $encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, "secret", 
  utf8_encode('changeme'), MCRYPT_MODE_ECB, $iv);
  echo $encrypted_string;
?>

结果: c811f6fe09f61abcf57623fc43554a17

我希望我在下面指定的代码给出相同的结果,但结果不一样,这可能是什么原因?

def PKCS5Padding(string):
    byteNum = len(string)
    packingLength = 8 - byteNum % 8
    appendage = chr(packingLength) * packingLength
    return string + appendage

def enc(string):
    key = b'secret'
    c1 = Blowfish.new(key, Blowfish.MODE_ECB)
    packedString = PKCS5Padding(string)
    return c1.decrypt(packedString.encode())
print(hashlib.md5(enc('changeme')).hexdigest())

结果: 08c74df87caf3ed8456f0e01a4b7234b

您在 Python 代码中调用c1.decrypt()而不是c1.encrypt() ,并且 PHP 代码(在mcrypt_encrypt()内部)只是将明文填充为 8 字节的倍数和空字节。 以下给出与 PHP 代码相同的结果: md5(0x9da1192c5d3b3072) == 0xe3b3884a2e3986a01b8d750f9d724ff8

def enc(plaintext):
    key = b'secret'
    c1 = Blowfish.new(key, Blowfish.MODE_ECB)
    encoded = plaintext.encode()
    padded = encoded.ljust((len(encoded) + 7) // 8 * 8, b'\0')
    return c1.encrypt(padded)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM