【问题标题】:Why mcrypt_encrypt returns a non readable character string为什么 mcrypt_encrypt 返回一个不可读的字符串
【发布时间】:2015-01-13 07:13:06
【问题描述】:

我尝试使用 rinjndael_128 密码的 ecb 模式使用 16 位密钥加密数据。加密成功,我也可以成功解密加密数据。但问题是,mcrypt_encrypt 函数返回的是乱码字符串。我想以十六进制格式查看此结果。

当我使用在线工具获取相同的数据时,得到这个十六进制值作为结果bd61ce515890e2e3fb5e404bbe886cc2

代码

$key = pack('H*', "07070609070306050601070007000700");
$plaintext = "2dfb0998b2f76f35f5b08972b57cfbfc";   
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_ECB);
$ciphertext_base64 = base64_encode($ciphertext);
echo  "encrypted - text: ".$ciphertext . "<br>";
echo  "encrypted base 64 encoded - text: ".$ciphertext_base64 . "<br>";

$ciphertext_dec = base64_decode($ciphertext_base64);
$plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,$ciphertext_dec, MCRYPT_MODE_ECB);
echo  "decrypted data - text: ".$plaintext_dec . "<br>";

结果:

before encryption - text: 2dfb0998b2f76f35f5b08972b57cfbfc
encrypted - text: (MÓx‹ÓåBÖ i½4²5žNUXÃè/Óë£@ö
encrypted base 64 encoded - text: KE3TeIsa0+VC1g1pCL00sjWeTlVYw+iNgS/TEOujQPY=
decrypted data - text: 2dfb0998b2f76f35f5b08972b57cfbfc*

【问题讨论】:

    标签: php encryption aes encryption-symmetric


    【解决方案1】:

    RIJNDAEL-128/ECB 的块大小是……嗯 128 位,即 16 字节。
    但是您当前的输入是 32 字节,因此输出也是两个块,即 32 字节长。

    您的明文看起来像密钥一样是“十六进制编码”的。所以,把它当作钥匙。
    此外 base64_encode() 与从字节序列制作“十六进制字符串”不同。但是你可以使用unpack()

    <?php
    $key = pack('H*', '07070609070306050601070007000700');
    $plaintext = pack('H*', '2dfb0998b2f76f35f5b08972b57cfbfc');
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_ECB);
    list(,$ciphertext_hex) = unpack('H*', $ciphertext);
    echo $ciphertext_hex;
    

    打印bd61ce515890e2e3fb5e404bbe886cc2

    【讨论】:

      猜你喜欢
      • 2010-10-04
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多