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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?