如何使用正确的php函数使用CryptoJS的加密方法

时间:2019-04-12 10:08:56

标签: php cryptojs

我有用于加密的javascript代码:

var myPassword = '12345*abc';
var encrypted   = CryptoJS.AES.encrypt(myString, myPassword);
document.getElementById("demo1").innerHTML = encrypted;

并且我有这样的php解密功能:

function decrypt($ciphertext, $key) {
   $ciphertext = base64_decode($ciphertext);
   if (substr($ciphertext, 0, 8) != "Salted__") {
      return false;
   }
   $salt = substr($ciphertext, 8, 8);
   $keyAndIV = evpKDF($key, $salt);
   $decryptPassword = openssl_decrypt(
        substr($ciphertext, 16), 
        "aes-256-cbc",
        $keyAndIV["key"], 
        OPENSSL_RAW_DATA, // base64 was already decoded
        $keyAndIV["iv"]);

   return $decryptPassword;
}

function evpKDF($password, $salt, $keySize = 8, $ivSize = 4, $iterations = 1, $hashAlgorithm = "md5") {
$targetKeySize = $keySize + $ivSize;
$derivedBytes = "";
$numberOfDerivedWords = 0;
$block = NULL;
$hasher = hash_init($hashAlgorithm);
while ($numberOfDerivedWords < $targetKeySize) {
    if ($block != NULL) {
        hash_update($hasher, $block);
    }
    hash_update($hasher, $password);
    hash_update($hasher, $salt);
    $block = hash_final($hasher, TRUE);
    $hasher = hash_init($hashAlgorithm);

    // Iterations
    for ($i = 1; $i < $iterations; $i++) {
        hash_update($hasher, $block);
        $block = hash_final($hasher, TRUE);
        $hasher = hash_init($hashAlgorithm);
    }

    $derivedBytes .= substr($block, 0, min(strlen($block), ($targetKeySize - $numberOfDerivedWords) * 4));

    $numberOfDerivedWords += strlen($block)/4;
}

return array(
    "key" => substr($derivedBytes, 0, $keySize * 4),
    "iv"  => substr($derivedBytes, $keySize * 4, $ivSize * 4)
);

}

到目前为止,它可以正常工作,现在我想用php函数对字符串进行加密,我尝试使用下面的代码之类的函数,但是它不起作用,

function encrypt($string, $key) {
   $salt = substr($string, 8, 8);
   $keyAndIV = evpKDF($key, $string);
   $encryptPassword = openssl_encrypt(
        $string,
        "aes-256-cbc",
        $keyAndIV["key"], 
        OPENSSL_RAW_DATA,
        $keyAndIV["iv"]);

  return $encryptPassword;

}

任何人都可以帮助我,我该如何解决此问题,谢谢。

0 个答案:

没有答案