phpphp-openssl

When attempting to decrypt an already encrypted string, no response is given


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

Using these 2 functions for encrypting and decrypting data, only my encrypting works.

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

// Response
DyUxPwraJyk=

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

// Doesn't respond with anything.

I have tried everything, even rewriting the functions multiple times but nothing seems to work.


Solution

  • The $iv option there is the "Initialization Vector", which acts sort of like a salt: it provides a different initial state for each message so that encrypting the same message twice is guaranteed to give different results.

    Like a salt, the IV should be chosen randomly when encrypting the message, and then transmitted or stored along with the message, so that when decrypting the message you can provide the same value.

    Probably you want your encrypt function to append $iv to the output, and decrypt to separate them back 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