dongxixia6399 2019-04-12 10:08
浏览 168

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

I have javascript code for encryption like this :

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

and I have a decryption function with php like this :

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

}

so far it works fine, and now I want to encrypt the string with the php function, I try to use a function like the code below, but it doesn't work,

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;

}

can anyone help me please, how can I fix this issue, thanks.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 fluent的在模拟压强时使用希望得到一些建议
    • ¥15 STM32驱动继电器
    • ¥15 Windows server update services
    • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
    • ¥15 模糊pid与pid仿真结果几乎一样
    • ¥15 java的GUI的运用
    • ¥15 Web.config连不上数据库
    • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
    • ¥15 怎么配置广告联盟瀑布流
    • ¥15 Rstudio 保存代码闪退