Replacing JAVA with PHP for PKCS5 encryption

前端 未结 3 1377
抹茶落季
抹茶落季 2021-02-09 12:16

I have been tasked with replacing a legacy java system with something which runs PHP.

I am getting a little stuck on replacing the java cryptography with PHP code.

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-09 12:51

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

    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);
      }
    

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

    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);
    

提交回复
热议问题