简体   繁体   English

将加密文本存储在数据库中,根据密码查询和解密

[英]Store encrypted texts in the database , query and decrypt it back base on password

I'm trying to store an encrypted text in my database, but I have no idea how to decrypted it back.我试图在我的数据库中存储一个加密的文本,但我不知道如何将它解密回来。 I've tried我试过了

$salt   = 'c0d4#';
$pepper ='nsa-cia-fbi'; // secret text

$pwd_peppered = hash_hmac("sha256", $salt, $pepper);
$pwd_hashed = password_hash($pwd_peppered, PASSWORD_ARGON2ID);

echo($pwd_hashed);

// right password hash 
$pwd_hashed = '$argon2id$v=19$m=65536,t=4,p=1$QnVpT1Rqay5WSmIvRW1HZg$rgx+DWPl5bvjwlr7plnOjnE1Sf8lim01pwb6lHGzEaU';

//wrong password hash : for testing purposes 
$pwd_hashed_wrong = '$argon2id$v=19$m=65536,t=4,p=1$QnVpT1Rqay5WSmIvRW1HZg$rgx+DWPl5bvjwlr7plnOjnE1Sf8lim01pwb6lHGzEaU-wrong-!!';

if (password_verify($pwd_peppered, $pwd_hashed)) {
    echo "Password matches.";

   // I am inside this block of codes, but ... 
   // no idea how to decrypt and get my text back ... 😵



}
else {
    echo "Password incorrect.";
}

you cannot decrypt a hashed text, if you want to make a password verification you have to hash the password entered by the user and test it with the hash of the real password (see if the 2 hash are equaled or not )您无法解密散列文本,如果您想进行密码验证,您必须将用户输入的密码 hash 与真实密码的 hash 进行测试(查看 2 hash 是否相等)

there is two concepts, hash and encrypt .有两个概念, hashencrypt when you hash a string, you can not turn it back to the original string.当你 hash 一个字符串时,你无法将它转回原来的字符串。 passwords must be hashed and then you are allowed to store them.密码必须经过哈希处理,然后您才可以存储它们。 If you encrypt a string you can turn result back to original string.如果您加密一个字符串,您可以将结果恢复为原始字符串。 In laravel you can use Illuminate\Support\Facades\Crypt class. there is an example:在 laravel 你可以使用Illuminate\Support\Facades\Crypt class。有一个例子:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Store a secret message for the user.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function storeSecret(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $user->fill([
            'secret' => encrypt($request->secret)
        ])->save();
    }
}

or或者

use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString('Hello world.');

$decrypted = Crypt::decryptString($encrypted);

as mentioned in this documentation by laravel .laravel文档中所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM