I know saving passwords in plain text is in a database is bad, but I need to save the password in a way that the users can retrieve and view them.
The Database will be located within our web host and access to it will be restricted to known IP Addresses, the actual scripts that will be accessing the database will be located in a different datacentre which is locked down for all access to our specific known IP Addresses.
What I'm thinking of doing is creating an encryption key based on the unique school name, location and a 64 digit string. This will secure the password which will then be saved into the database.
To decrypt this, the script will have to read the school name and location from the DB and add the 64 digit string and then decrypt the password to display to the user.
When this goes live the 64 digit string won't be saved in the script it will be passed on the URL.
Using this https://stackoverflow.com/a/57249681/2134973 I've managed to get the password to be encrypted and decrypted. But as soon as I save the encrypted password to the database, it fails to decrypt when read back from the Database.
The code I have so far is: From the initial database read I have :
$school = $db['school'];
$location = $db['location'];
$password = $db['password']; // plain text
I then encrypt using:
define('ENCRYPTION_KEY', "{$school}r$qVsYRk4*&H?=pb9sRdJHLbtERBwGSxezJa5eG?Zb#SrC&q2yzHLE=BjU?Wm9sM{$location}");
$OpensslEncryption = new Openssl_EncryptDecrypt;
$encrypted = $OpensslEncryption->encrypt($password, ENCRYPTION_KEY);
and save $encrypted
back to my database.
For decrypting it I'm reading the data from the database and processing it as:
$school = $db['school'];
$location = $db['location'];
$password = $db['password']; // encrypted
define('ENCRYPTION_KEY', "{$school}r$qVsYRk4*&H?=pb9sRdJHLbtERBwGSxezJa5eG?Zb#SrC&q2yzHLE=BjU?Wm9sM{$location}");
$OpensslEncryption = new Openssl_EncryptDecrypt;
$decrypted = $OpensslEncryption->decrypt($password, ENCRYPTION_KEY);
If I var_dump $decrypted
I get NULL.
If I dump the $encrypted
and $password
(after encryption) they are both the same string length.
The field in the database is defined as VARCHAR 1024
Can anyone advise how to do this, or if there is a better more secure way.
Ultimately I need to user to be able to see the passwords as plain text, but store them as securely as possible.
Thanks
UPDATE
The password held in the database don't belong to the users who are logged in. They are passwords to our internal systems which are all IP authenticated as well.
The users need to see these passwords.
";echo '$aVar
'; ` and see the differece. In this string `"{$school}r$qVsYRk4*&H?=pb9s"` `$qVsYRk4` is considered an undefined variable. – Juan Apr 19 '20 at 15:59