Q. Symmetric encryption is a type of encryption where the same key is used to encrypt and decrypt the message. Can you explain how do I use symmetric encryption under PHP to store password in a text file and authenticate the user?

A. Symmetric encryption differs from asymmetric (also known as public-key) encryption, which uses one key to encrypt a message and another to decrypt the message.

PHP crypt() will return an encrypted string using the standard Unix DES-based encryption algorithm or alternative algorithms that may be available on the system. Arguments are a string to be encrypted and an optional salt string to base the encryption on. See the Unix man page for your crypt function for more information.

string crypt ( string $str [, string $salt] )

Consider following example.
$en_password : Stores encrypted password. You need to store this in database or flat text file.
$userPasswordInput : Holds user provided / supplied password via HTML page

If command is use to check encrypted password (hash) with user supplied password.

//Standard DES-based encryption with a two character salt called 'ge'
$en_password = crypt('secrete','ge');

if (crypt($userPasswordInput, $en_password) == $en_password) {
   echo "Password verified, you can login!";

PHP Function to write / store password to a file called /home/secure/.password

function updateAdminLoginPassword($new){
  //This is Blowfish encryption with a sixteen character salt starting with or $2a$
  $encryptedPassword = crypt($new, '$2a$didIL...fpSd78..$');
  // Open the file and erase the contents if any
  $fp = fopen("/home/secure/.password", "w");
  // Write the data to the file
  fwrite($fp, $Password);
  // Close the file
  echo '<h3>Password has been updated!<h3>';
  echo '<SCRIPT>alert(\'Password changed! You must login again to use new password\');</SCRIPT>';
  /* resetSession(); */

Function to verify a password (note we are using hash in both functions $2a$didIL…fpSd78..$):

function verifyPassword($password)
 $username= "admin"; 
// read encrypted password
 $fp = fopen("/home/secure/.password", "r");
 while ( $line = fgets($fp, 1000) ) { $encryptedpasswd=$line; }
 if ( $_POST["username"] == $username && (crypt($password,'$2a$didIL...fpSd78..$') ==  $encryptedpasswd) )
 { // allow login
		session_start(); //Initialize session data
                //store user login name and password
		$_SESSION['user'] = $username;
                $_SESSION['pwd'] = $encryptedpasswd;  
                // display main menu
		header( "Location: /welcome.php" );
 {       // password is not correct or session expired due to password change
	header( "Location: /login.php?sessionnotfound=1" );

Above examples just provides you idea about php password encryptions and hash. You must consider other factors such as SSL http session, MD5 password / hash and mysql database to store password has etc.

Further readings:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 2 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
2 comments… add one
  • naqiya Jan 1, 2011 @ 17:00

    hi ,can i have help from you i want to write php code for encrypt login password using DES algorithm please.

  • Kerrie Minifield Oct 12, 2011 @ 9:16

    hey there and thank you for your info – I’ve certainly picked up something new from right here. I did however expertise a few technical points using this site, as I experienced to reload the web site lots of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Well I’m adding this RSS to my email and could look out for much more of your respective intriguing content. Ensure that you update this again very soon..

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum