簡體   English   中英

如何使用libsodium php用salt加密/解密密碼

[英]how to encrypt / decrypt password with salt using libsodium php

我想要得到的是

  • 用libsodium加密密碼+ salt
  • 將其存儲到數據庫
  • 讀取並解密(取回普通密碼進行身份驗證)

我得到了要用於加密/解密密碼的鹽列表。 當我對密碼進行加密時,我會得到一個散列,以便看起來似乎可以工作,但是在解密時,我總是得到false作為返回值。

我使用錯誤的方法使用libsodium進行加密/解密還是完全朝錯誤的方向行駛?

我的加密/解密來源:

function encrypt_libsodium($to_encrypt, $salt_to_use){
        if(!$data || !$salt_to_use){
            return null;
        }

        //get stored salt
        $this->key_ = substr(md5($this->pw_key[$salt_to_use].'_'), 0, $this->ks);

        //some libsodium specific stuff
        $out_len = \Sodium\CRYPTO_SIGN_SEEDBYTES;
        $ops_limit = \Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE;
        $mem_limit =\Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE;

        //create hash using libsodium
        $hash = \Sodium\crypto_pwhash($out_len, $to_encrypt, $this->key_,$ops_limit, $mem_limit);
        return $hash;
    }

    function decrypt_libsodium($hash, $salt_to_use){
        if(!$hash || !$what){
            return null;
        }

        //get stored salt
        $this->key_ = substr(md5($this->pw_key[$salt_to_use].'_'), 0, $this->ks);

        //get verification hash
        $decrypted = \Sodium\crypto_pwhash_scryptsalsa208sha256_str_verify($this->key_, $hash);
        return $decrypted;
    }

感謝您的幫助!

問候唐

看起來您正在嘗試混合許多不相關的內容。 CRYPTO_SIGN_SEEDBYTES用於簽名,與密碼哈希無關, crypto_pwhash不使用scrypt算法,因此CRYPTO_PWHASH_SCRYPTSALSA208SHA256_*常量不適用,我不確定md5()在這里做什么。 您可能希望散列密碼,而不是對其進行加密。

無論如何, crypto_pwhash_str()函數可以完成您需要的一切。 它創建一個salt,對密碼進行哈希處理,並將結果(連同salt,算法及其參數)編碼為可以直接存儲到數據庫中的字符串:

$password = 'correct horse battery staple';
$h = \Sodium\crypto_pwhash_str($password,                                   
         \Sodium\CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
         \Sodium\CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE);

$h是您需要存儲在數據庫中的全部。

然后,要驗證數據庫中的內容對於給定密碼是否有效:

if (\Sodium\crypto_pwhash_str_verify($h, $password) === FALSE) {
    // wrong password!
}

如果您不需要專門使用libsodium,則可以使用此功能將加密的數據存儲在數據庫中並解密。

define("ENCRYPT_METHOD", "AES-256-CBC");
define("SECRET_KEY","randomtextrandomtextforthesecretkey");
define("SECRET_IV", "randomtextforthesecretiv");
function encriptar($action, $string)
{
  $output = false;
  $key    = hash("sha256", SECRET_KEY);
  $iv     = substr(hash("sha256", SECRET_IV), 0, 16);

  if ($action == "encrypt")
  {
    $output = openssl_encrypt($string, ENCRYPT_METHOD, $key, 0, $iv);
    $output = base64_encode($output);
  }
  else if($action == "decrypt")
    {
        $output = base64_decode($string);
        $output = openssl_decrypt($output, ENCRYPT_METHOD, $key, 0, $iv);
    }
  return $output;
}

輸出將是您將存儲/獲取到數據庫的數據。

暫無
暫無

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

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