Unable to exchange data encrypted with AES-256 between Java and PHP

前端 未结 4 1574
陌清茗
陌清茗 2020-12-04 22:51

My problem is: what I encrypt in Java I can decrypt perfectly in Java, but PHP mcrypt can\'t decrypt. What I encrypt with mcrypt I can decrypt with

4条回答
  •  生来不讨喜
    2020-12-04 23:32

    I know this is an old topic, but I will add my working solution.

    You have to rewrite PHP side of the script:

    function getEncrypt($sStr, $sKey) {
      return base64_encode(
        mcrypt_encrypt(
            MCRYPT_RIJNDAEL_128, 
            base64_decode($sKey),
            $sStr,
            MCRYPT_MODE_ECB
        )
      );
    }
    
    function getDecrypt($sStr, $sKey) {
      return mcrypt_decrypt(
        MCRYPT_RIJNDAEL_128, 
        base64_decode($sKey), 
        base64_decode($sStr), 
        MCRYPT_MODE_ECB
      );
    }
    

    You should base64_decode($sKey) because your key is base64 encoded.

    $key = "Zvzpv8/PXbezPCZpxzQKzL/FeoPw68jIb+NONX/LIi8=";
    

    Then, you need to create this function (credit goes to beltrachi from http://www.php.net/manual/en/function.mcrypt-decrypt.php):

    function pkcs5_pad ($text, $blocksize) { 
      $pad = $blocksize - (strlen($text) % $blocksize); 
      return $text . str_repeat(chr($pad), $pad); 
    }
    

    Use this code do encode/decode:

    $decrypt = getDecrypt("6XremNEs1jv/Nnf/fRlQob6oG1jkge+5Ut3PL489oIo=", $key);
    echo $decrypt;
    echo "\n\n";
    echo getEncrypt(pkcs5_pad("My very secret text:)", 16), $key);
    

    I hope this will be useful for someone! :)

提交回复
热议问题