Peer
Peer

Reputation: 133

Is it possible to encrypt data in Laravel with APP_KEY which differ per user?

I'm using the Laravel framework to encrypt almost all data in a MySQL database. This is a requirement, due to privacy concerns.

Laravel uses an application specific APP_KEY as the main key to handle encryption and decryption (OpenSSL / AES-256-CBC cipher).

I wonder: Is it easy (or is there a package) to generate an APP_KEY on a user base? So each user get's an APP_KEY (f.e. USER_APP_KEY) to handle all user specific data?

I think this adds an extra security layer. So even if the data is stolen and one user is somehow decrypted, the rest of the data remains useless to the attacker.

Or am i overcomplicating things and is a single APP_KEY safe enough?


Already tried:

Search for existing packages for Laravel framework. Generic Google search for examples.

Upvotes: 3

Views: 3145

Answers (2)

IshaS
IshaS

Reputation: 837

Yes you can generate the key for every user and store it into the users table. Following code sample is to generate a key.

'key' => encrypt($this->generateRandomString(16))

private function generateRandomString($n) { 

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 

    $randomString = ''; 
    for ($i = 0; $i < $n; $i++) { 

        $index = rand(0, strlen($characters) - 1); 

        $randomString .= $characters[$index]; 

    }      

    return $randomString; 

} 

When you need to decrypt the content, you can do it as follows.

$encrypter = new \Illuminate\Encryption\Encrypter($key);
$decrypted = $encrypter->decrypt($encryptedContent);

For additional security, I suggest you to encrypt the user based key using APP_KEY. Then store encrypted key in the database.

When decrypt, you need to decrypt the key first. After you can decrypt the content using user based key. Then some one need to get the content need to know both two keys which are user key and app key.

Hope this helps.

Upvotes: 2

Peer
Peer

Reputation: 133

Decided to go with a single APP_KEY. There's is no package that i'm aware of that handles this. And based on the comments, it doesn't do any good in terms of security.

Upvotes: 0

Related Questions