簡體   English   中英

嘗試解密已加密的字符串時,未給出響應

[英]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);
}

使用這兩個函數來加密和解密數據,只有我的加密工作。

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

// Response
DyUxPwraJyk=

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

// Doesn't respond with anything.

我已經嘗試了一切,甚至多次重寫函數,但似乎沒有任何效果。

那里的$iv選項是“初始化向量”,它的作用有點像鹽:它為每條消息提供不同的初始狀態,因此可以保證兩次加密相同的消息會產生不同的結果。

像鹽一樣,IV 應該在加密消息時隨機選擇,然后與消息一起傳輸或存儲,以便在解密消息時可以提供相同的值。

可能您希望您的encrypt函數將$iv附加到輸出,並decrypt以將它們分開。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM