I'm using the PHP mcrypt
library to cryptograph and store (MySQL
) data using AES.
I was wondering if there is a good way to do this without having a hardcoded encryption/decryption key in my code.
If a hacker gets access to my server he will be able to see the files and my key on the code, therefore accessing all the data on the database.
Thanks.
I'm using the PHP
mcrypt
library to cryptograph and store (MySQL
) data using AES.
You may wish to reconsider your choice in cryptography library.
I was wondering if there is a good way to do this without having a hardcoded encryption/decryption key in my code.
Store it in a configuration file outside your document root? For example, defuse/php-encryption.
If a hacker gets access to my server he will be able to see the files and my key on the code, therefore accessing all the data on the database.
If a hacker gets access to your server, symmetric-key encryption cannot save you. Public-key encryption, however, can preserve confidentiality.
Using Halite, this is easy to solve:
<?php
declare(strict_types=1);
use ParagonIE\Halite\{
Asymmetric\Crypto as Asymmetric,
KeyFactory
};
$publicKey = KeyFactory::loadEncryptionPublicKey("/path/to/public/key");
$encrypted = Asymmetric::seal("Whatever secret data we want", $publicKey);
// Now do whatever you need with $encrypted
<?php
declare(strict_types=1);
use ParagonIE\Halite\{
Asymmetric\Crypto as Asymmetric,
KeyFactory
};
$salt = ""; // Generate from random_bytes(16) once, then persist.
$password = ""; // Create a strong password
$keyPair = KeyFactory::deriveEncryptionKeyPair($password, $salt);
$secretKey = $keyPair->getSecretKey();
$publicKey = $keyPair->getPublicKey();
// To have the public key to a file to upload to the server:
KeyFactory::save($publicKey, '/path/to/public/key');
$decrypted = Asymmetric::unseal($encrypted, $secretKey);
It depends to what lengths you're willing to go, and your environment.
It's definitely a bad idea to keep the decryption key in the database - if anyone gets a hold of the database, they'll have both the decryption key and the data. By storing it on the application server, you can be certain that the above won't happen. But what if someone gets access to the application server, and then to the database through the application server? Now they have both the key and the data again. But this much you've said already.
Since you didn't mention your environment, let's assume:
You could have a simple Apache configuration file that:
Then during deployment:
After this, the current state of things will be:
How you could still be vulnerable:
Still, it's a lot safer than storing the unencrypted key on the application server, and it requires a very involved and highly sophisticated attacker to exploit. So, as I said at the beginning, it depends what lengths you want to go to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With