简体   繁体   中英

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 )

there is two concepts, hash and encrypt . when you hash a string, you can not turn it back to the original string. 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:

<?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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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