0

我正在尝试创建一个简单的 Encryption 类,但结果字符串正在用非 ascii 字符填充。我已经尝试了 rtrim(),转换为 utf8 等,如其他一些答案中所述。我到底错过了什么?这是将结果粘贴到 Notepad++ 时显示的字符

在此处输入图像描述

Pastebin 包含这里的字符。在 html 中显示为“t”,但将其复制到记事本中会显示其后的随机数据位。

class Crypter implements ICrypter {

private $Key;
private $Algo;

public function __construct($Algo = MCRYPT_BLOWFISH) {

    $this->Key = substr('key', 0, mcrypt_get_key_size($Algo, MCRYPT_MODE_ECB));
    $this->Algo = $Algo;

}

public function Encrypt($data) {

    //$iv_size = mcrypt_get_iv_size($this->Algo, MCRYPT_MODE_ECB);
    //$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    $blocksize = mcrypt_get_block_size('blowfish', 'ecb'); // get block size
    $pkcs = $blocksize - (strlen($data) % $blocksize); // get pkcs5 pad length
    $data.= str_repeat(chr($pkcs), $pkcs); // append pkcs5 padding to the data


    $crypt = mcrypt_encrypt($this->Algo, $this->Key, $data, MCRYPT_MODE_ECB);
    return rtrim(base64_encode($crypt));

}

public function Decrypt($data) {

    $crypt = base64_decode($data);
    $iv_size = mcrypt_get_iv_size($this->Algo, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypt = mcrypt_decrypt($this->Algo, $this->Key, $crypt, MCRYPT_MODE_ECB, $iv);
    return rtrim($decrypt);
}
 }
4

1 回答 1

5

您需要在解密中处理与加密相同的填充。这是您的代码的一个工作示例:

<?php
class Crypter{

    private $Key;
    private $Algo;

    public function __construct($Algo = MCRYPT_BLOWFISH) {

        $this->Key = substr('key', 0, mcrypt_get_key_size($Algo, MCRYPT_MODE_ECB));
        $this->Algo = $Algo;

    }

    public function Encrypt($data) {

        //$iv_size = mcrypt_get_iv_size($this->Algo, MCRYPT_MODE_ECB);
        //$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

        $blocksize = mcrypt_get_block_size('blowfish', 'ecb'); // get block size
        $pkcs = $blocksize - (strlen($data) % $blocksize); // get pkcs5 pad length
        $data.= str_repeat(chr($pkcs), $pkcs); // append pkcs5 padding to the data


        $crypt = mcrypt_encrypt($this->Algo, $this->Key, $data, MCRYPT_MODE_ECB);

        return rtrim(base64_encode($crypt));

    }

    public function Decrypt($data) {

        $crypt = base64_decode($data);
        $iv_size = mcrypt_get_iv_size($this->Algo, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decrypt = mcrypt_decrypt($this->Algo, $this->Key, $crypt, MCRYPT_MODE_ECB, $iv);

        $block = mcrypt_get_block_size('blowfish', 'ecb');
        $pad = ord($decrypt[($len = strlen($decrypt)) - 1]);
        return substr($decrypt, 0, strlen($decrypt) - $pad);
    }
}

$crypter = new Crypter();
$data = "Some data to encrypt";
$encryptedData = $crypter->Encrypt($data);
$decryptedData = $crypter->Decrypt($encryptedData);
echo "Decrypted Data = [$decryptedData]\n";

请注意我用三行替换了您原来的Decrypt()返回行。

于 2013-04-12T03:14:27.940 回答