使用Rijndael(AES)解密会在字符串末尾返回垃圾文本

时间:2017-02-17 10:00:16

标签: php

这是我用来加密和解密文本的类:

class Cipher {

    private $key, $iv;

    function __construct() {

        $this->key = "edrtjfjfjlldldld";
        $this->iv = "5666685225155700988888995512AbCd";
    }

    function encrypt($text) {

        $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $padding = $block - (strlen($text) % $block);
        $text .= str_repeat(chr($padding), $padding);
        $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->key, $text, MCRYPT_MODE_CBC, $this->iv);

        return rtrim(base64_encode($crypttext),"\0");
    }

    function decrypt($input) {

        $dectext = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->key, base64_decode($input), MCRYPT_MODE_CBC, $this->iv),"\0");
        return $dectext;
    }
}

输出:

Input : 103500.00
Encrypt: or+JRAS+lnLVcHgKfrV8URMAdWLs440EEapTT7PlQck=
Decrypt: 103500.00(+garbled characters)

为什么解密文本中存在垃圾字符?

2 个答案:

答案 0 :(得分:0)

尝试以下功能在应用程序上完美运行 这里 $ q是$输入。

function encryptIt( $q ) {
      $cryptKey  = 'qJB0rGtInRCD5UB1xG03efyCpRKRV';
      $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
      return( $qEncoded );
    }

function decryptIt( $q ) {
  $cryptKey  = 'qJB0rGtInRCD5UB1xG03efyCpRKRV';
  $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
  return( $qDecoded );
}

答案 1 :(得分:0)

我会说它有一些东西要处理填充或密钥大小。你要求RIJNDAEK 256位,但提供128位密钥。