且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用PHP替换JAVA以进行PKCS5加密

更新时间:2023-11-23 18:47:40

现有的答案都对您有所帮助,但我将在此处发布完整的解决方案.

Both existing answers helped, but I'll post the complete solution here.

我在任何地方都没有看到它的文档,但是在查看了该加密方案的实现之后,我发现密钥是加密哈希的前8个字节,IV是后8个字节.

I have not seen it documented anywhere but after looking at implementations for this encryption scheme I found the key is the first 8 bytes of the encrypted hash and the IV is the last 8.

 public function get_key_and_iv($key, $salt, $reps) {
    $hash = $key . $salt;
    for ($i = 0; $i< $reps; $i++) {
      $hash = md5($hash, TRUE);
    }
    return str_split($hash,8);
  }

似乎可以解决问题.它在我的问题中替换了pbkdf2,否定了< GUESS 1> 的需求,并为< GUESS 2>

seems to do the trick. Which replaces pbkdf2 in my question, negates the need for <GUESS 1> and gives a value for <GUESS 2>

然后,我陷入了詹姆斯·布莱克(James Black)提到并设法解决的填充问题.所以最终的代码是

Then I got caught with the padding problem which James Black mentioned and managed to fix. So final code is

list($hashed_key, $iv) = get_key_and_iv($key, $salt, $reps);
// 8 is DES block size.
$pad = 8 - (strlen($plaintext) % 8);
$padded_string = $plaintext . str_repeat(chr($pad), $pad);
return mcrypt_encrypt(MCRYPT_DES, $hashed_key, $padded_string, MCRYPT_MODE_CBC, $iv);