首页  >  问答  >  正文

尝试解密已加密的字符串时未收到响应

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

使用这两个函数来加密和解密数据,只有我的加密有效。

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

// Response
DyUxPwraJyk=

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

// Doesn't respond with anything.

我已经尝试了一切,甚至多次重写函数,但似乎没有任何效果。

P粉186904731P粉186904731257 天前324

全部回复(1)我来回复

  • P粉895187266

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

    $iv 选项有“初始化向量”,它的作用有点像盐:它为每条消息提供不同的初始状态,以便保证对同一消息加密两次不同的结果。

    就像盐一样,在加密消息时应随机选择 IV,然后与消息一起传输或存储,以便在解密消息时可以提供相同的值。

    您可能希望您的加密函数将$iv附加到输出,并解密将它们分离出来。

    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

    回复
    0
  • 取消回复