PHP加密/解密添加填充字符

时间:2013-04-12 01:29:03

标签: php encryption character-encoding blowfish password-encryption

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

enter image description here

包含字符here的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);
}
 }

1 个答案:

答案 0 :(得分: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()返回行替换了三行。