Home  >  Q&A  >  body text

No response received when trying to decrypt encrypted string

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粉186904731P粉186904731306 days ago352

reply all(1)I'll reply

  • P粉895187266

    P粉8951872662024-01-11 15:59:17

    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

    reply
    0
  • Cancelreply