No response received when trying to decrypt encrypted string
P粉186904731
P粉186904731 2024-01-10 17:43:06
0
1
386

function encrypt($string, $key)
{
    $method = "BF-CBC";
    $iv = random_bytes(openssl_cipher_iv_length($method));
    $options = 0;
    $key = hash("sha256", $key);
    return openssl_encrypt($string, $method, $key, $options, $iv);
}

function decrypt($string, $key)
{
    $method = "BF-CBC";
    $iv = random_bytes(openssl_cipher_iv_length($method));
    $options = 0;
    $key = hash("sha256", $key);
    return openssl_decrypt($string, $method, $key, $options, $iv);
}

Use these two functions to encrypt and decrypt data, only my encryption works.

// Encrypting foo 
echo encrypt("foo", "hfgdhgdfhgfd");

// Response
DyUxPwraJyk=

// Decrypting DyUxPwraJyk= 
echo decrypt("DyUxPwraJyk=", "hfgdhgdfhgfd");

// Doesn't respond with anything.

I've tried everything, even rewriting the function multiple times, but nothing seems to work.

P粉186904731
P粉186904731

reply all(1)
P粉895187266

The

$iv option has an "initialization vector", which acts a bit like a salt: it provides a different initial state for each message, so as to guarantee different results for encrypting the same message twice.

Just like the salt, the IV should be randomly selected when encrypting the message and then transmitted or stored with the message so that the same value can be provided when decrypting the message.

You may want your encryption function to append $iv to the output, and decrypt to separate them out.

function encrypt($string, $key)
{
    $method = "BF-CBC";
    $iv = random_bytes(openssl_cipher_iv_length($method));
    $options = 0;
    $key = hash("sha256", $key);
    return base64_encode($iv)
        . '|'
        . openssl_encrypt($string, $method, $key, $options, $iv);
}

function decrypt($encryptedString, $key)
{
    $method = "BF-CBC";
    [ $iv, $ciphertext ] = explode('|', $encryptedString, 2);
    $iv = base64_decode($iv);
    $options = 0;
    $key = hash("sha256", $key);
    return openssl_decrypt($ciphertext, $method, $key, $options, $iv);
}

echo encrypt("foo", "hfgdhgdfhgfd");
# fJTTArVw8e8=|zJOHacxbs1Q=

echo decrypt("fJTTArVw8e8=|zJOHacxbs1Q=", "hfgdhgdfhgfd");
# foo
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template