普通网友 2015-01-22 17:00
浏览 135

加密/解密会导致字符串开头的替换和不正确的字符

Here are my encrypt and decrypt functions

public function encrypt($text){
        $key = hash("md5", KEY);
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_TWOFISH, MCRYPT_MODE_CBC), MCRYPT_RAND);
        $result = base64_encode(mcrypt_encrypt(MCRYPT_TWOFISH, $key, $text, MCRYPT_MODE_CBC, $iv));
        return $result;
}

public function decrypt($text){
        $key = hash("md5", KEY);
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_TWOFISH, MCRYPT_MODE_CBC), MCRYPT_RAND);
        $result = trim(mcrypt_decrypt(MCRYPT_TWOFISH, $key, base64_decode($text), MCRYPT_MODE_CBC, $iv));    
        return $result;
}

When encryption is run on a JSON string to be stored as a text file and then retrieved and decrypted the front section of the resulting string has replacement and/or incorrect characters:

Expected:

{"players":[{"label":"...

Actual:

�Ӹ�!G@${�W�Rՙ�bel":"...

If it makes any difference the actual placement/incorrect chars are different each time I refresh the page on the same file.

  • 写回答

1条回答 默认 最新

  • dongyun6229 2015-01-23 13:31
    关注

    In case anyone comes across this...

    The IV needs to be prepended to the file before encoding, like so:

    public function encrypt($text){
        $key = hash("md5", KEY);
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_TWOFISH, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
        $result = base64_encode($iv.mcrypt_encrypt(MCRYPT_TWOFISH, $key, $text, MCRYPT_MODE_CBC, $iv));
        return $result;
    }
    

    Then when decrypting take the IV from the decoded string and use it to decrypt, like so:

    public function decrypt($text){
        $key = hash("md5", KEY);
        $decode = base64_decode($text);
        $iv = substr($decode, 0, 16);
        $decrypt = substr($decode, 16);
        $result = mcrypt_decrypt(MCRYPT_TWOFISH, $key, $decrypt, MCRYPT_MODE_CBC, $iv);
        return $result;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计一个单管共射放大电路
  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架