mrweb

How to decrypt data from encrypted database to show a list?

Posted 6 months ago by mrweb

I have a DB where some data are stored with encrypt($data) so that they get encrypted in the DB.

I need to make a DB select and join data between tables to return a list, but the data have to be decrypted before landing in the HTML.

So this is what I came up with:

public function contact() {
        $data = Contact::select('contacts.*', 'sources.name as fonte')
            ->leftJoin('sources', 'contacts.source_id', '=', 'sources.id')
            ->addSelect(DB::raw('(SELECT nota FROM notes WHERE contacts.id = notes.contact_id ORDER BY created_at DESC LIMIT 1) nota'))
            ->addSelect(DB::raw('(SELECT recall FROM notes WHERE contacts.id = notes.contact_id ORDER BY created_at DESC LIMIT 1) recall'))
            ->addSelect(DB::raw('(SELECT appointment FROM notes WHERE contacts.id = notes.contact_id ORDER BY created_at DESC LIMIT 1) appointment'))
            ->where('contacts.type', '=', 'buyer')
            ->get();

        foreach ($data as $encrypted_data => $encrypted) {
            $encrypted->nome    = decrypt($encrypted->nome);
            $encrypted->cognome = decrypt($encrypted->cognome);
            $encrypted->cell    = decrypt($encrypted->cell);
            $encrypted->phone   = decrypt($encrypted->phone);
            $encrypted->email   = decrypt($encrypted->email);
        }
        return ['data' => $data];
    }

I'm not sure the foreach is a good idea as it may suck up some CPU, if I list a 1000 record this will probably slow everything...

Any better way?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.