Skip to content

Instantly share code, notes, and snippets.

@etienne-martin
Created November 7, 2019 15:06
Show Gist options
  • Save etienne-martin/5e4405c587f624460910906887585c92 to your computer and use it in GitHub Desktop.
Save etienne-martin/5e4405c587f624460910906887585c92 to your computer and use it in GitHub Desktop.
Decrypt a crypto-js encrypted string with php
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)
);
}
function decrypt($ciphertext, $password){
$ciphertext = base64_decode($ciphertext);
if( substr($ciphertext, 0, 8) != "Salted__" ){
return false;
}
$salt = substr($ciphertext, 8, 8);
$keyAndIV = evpKDF($password, $salt);
$decryptPassword = openssl_decrypt(
substr($ciphertext, 16),
"aes-256-cbc",
$keyAndIV["key"],
OPENSSL_RAW_DATA, // base64 was already decoded
$keyAndIV["iv"]);
return $decryptPassword;
}
@e-ravanbakhsh12
Copy link

e-ravanbakhsh12 commented Apr 15, 2023

hi how can could i encrypted with php? i'm not wanna decrypted

below function working

function encrypt($ciphertext, $password) {

    $salted = "Salted__";
    $salt = openssl_random_pseudo_bytes(8);

    $keyAndIV = evpKDF($password,$salt);
    $encrypt  = openssl_encrypt(
           $ciphertext, 
            "aes-256-cbc",
            $keyAndIV["key"], 
            OPENSSL_RAW_DATA,
            $keyAndIV["iv"]);
    return  base64_encode($salted.$salt.$encrypt);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment