Authenticating plain text password against md5 hash - authentication

Hello and thank you for reading,
I have a task to authenticate a un / pw pair against a password stored in a MySQL database which has joomla serving as the CMS / frontend.
The joomla web application supports storing usernames and passwords in said database and it would appear that it goes through the following steps when storing a new user -
$salt = JUserHelper::genRandomPassword(32);
$crypt = JUserHelper::getCryptedPassword($array['password'], $salt);
$array['password'] = $crypt.':'.$salt;
genRandomPassword looks like -
/**
* Generate a random password
*
* #static
* #param int $length Length of the password to generate
* #return string Random Password
* #since 1.5
*/
public static function genRandomPassword($length = 8)
{
$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$len = strlen($salt);
$makepass = '';
$stat = #stat(__FILE__);
if (empty($stat) || !is_array($stat)) $stat = array(php_uname());
mt_srand(crc32(microtime() . implode('|', $stat)));
for ($i = 0; $i < $length; $i ++) {
$makepass .= $salt[mt_rand(0, $len -1)];
}
return $makepass;
}
Finally, getCryptedPassword and getSalt look like -
/**
* Formats a password using the current encryption.
*
* #access public
* #param string $plaintext The plaintext password to encrypt.
* #param string $salt The salt to use to encrypt the password. []
* If not present, a new salt will be
* generated.
* #param string $encryption The kind of pasword encryption to use.
* Defaults to md5-hex.
* #param boolean $show_encrypt Some password systems prepend the kind of
* encryption to the crypted password ({SHA},
* etc). Defaults to false.
*
* #return string The encrypted password.
*/
public static function getCryptedPassword($plaintext, $salt = '', $encryption = 'md5-hex', $show_encrypt = false)
{
// Get the salt to use.
$salt = JUserHelper::getSalt($encryption, $salt, $plaintext);
// Encrypt the password.
switch ($encryption)
{
case 'plain' :
return $plaintext;
case 'sha' :
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
return ($show_encrypt) ? '{SHA}'.$encrypted : $encrypted;
case 'crypt' :
case 'crypt-des' :
case 'crypt-md5' :
case 'crypt-blowfish' :
return ($show_encrypt ? '{crypt}' : '').crypt($plaintext, $salt);
case 'md5-base64' :
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
return ($show_encrypt) ? '{MD5}'.$encrypted : $encrypted;
case 'ssha' :
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext.$salt).$salt);
return ($show_encrypt) ? '{SSHA}'.$encrypted : $encrypted;
case 'smd5' :
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext.$salt).$salt);
return ($show_encrypt) ? '{SMD5}'.$encrypted : $encrypted;
case 'aprmd5' :
$length = strlen($plaintext);
$context = $plaintext.'$apr1$'.$salt;
$binary = JUserHelper::_bin(md5($plaintext.$salt.$plaintext));
for ($i = $length; $i > 0; $i -= 16) {
$context .= substr($binary, 0, ($i > 16 ? 16 : $i));
}
for ($i = $length; $i > 0; $i >>= 1) {
$context .= ($i & 1) ? chr(0) : $plaintext[0];
}
$binary = JUserHelper::_bin(md5($context));
for ($i = 0; $i < 1000; $i ++) {
$new = ($i & 1) ? $plaintext : substr($binary, 0, 16);
if ($i % 3) {
$new .= $salt;
}
if ($i % 7) {
$new .= $plaintext;
}
$new .= ($i & 1) ? substr($binary, 0, 16) : $plaintext;
$binary = JUserHelper::_bin(md5($new));
}
$p = array ();
for ($i = 0; $i < 5; $i ++) {
$k = $i +6;
$j = $i +12;
if ($j == 16) {
$j = 5;
}
$p[] = JUserHelper::_toAPRMD5((ord($binary[$i]) << 16) | (ord($binary[$k]) << 8) | (ord($binary[$j])), 5);
}
return '$apr1$'.$salt.'$'.implode('', $p).JUserHelper::_toAPRMD5(ord($binary[11]), 3);
case 'md5-hex' :
default :
$encrypted = ($salt) ? md5($plaintext.$salt) : md5($plaintext);
return ($show_encrypt) ? '{MD5}'.$encrypted : $encrypted;
}
}
/**
* Returns a salt for the appropriate kind of password encryption.
* Optionally takes a seed and a plaintext password, to extract the seed
* of an existing password, or for encryption types that use the plaintext
* in the generation of the salt.
*
* #access public
* #param string $encryption The kind of pasword encryption to use.
* Defaults to md5-hex.
* #param string $seed The seed to get the salt from (probably a
* previously generated password). Defaults to
* generating a new seed.
* #param string $plaintext The plaintext password that we're generating
* a salt for. Defaults to none.
*
* #return string The generated or extracted salt.
*/
public static function getSalt($encryption = 'md5-hex', $seed = '', $plaintext = '')
{
// Encrypt the password.
switch ($encryption)
{
case 'crypt' :
case 'crypt-des' :
if ($seed) {
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 2);
} else {
return substr(md5(mt_rand()), 0, 2);
}
break;
case 'crypt-md5' :
if ($seed) {
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 12);
} else {
return '$1$'.substr(md5(mt_rand()), 0, 8).'$';
}
break;
case 'crypt-blowfish' :
if ($seed) {
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 16);
} else {
return '$2$'.substr(md5(mt_rand()), 0, 12).'$';
}
break;
case 'ssha' :
if ($seed) {
return substr(preg_replace('|^{SSHA}|', '', $seed), -20);
} else {
return mhash_keygen_s2k(MHASH_SHA1, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
}
break;
case 'smd5' :
if ($seed) {
return substr(preg_replace('|^{SMD5}|', '', $seed), -16);
} else {
return mhash_keygen_s2k(MHASH_MD5, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
}
break;
case 'aprmd5' :
/* 64 characters that are valid for APRMD5 passwords. */
$APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if ($seed) {
return substr(preg_replace('/^\$apr1\$(.{8}).*/', '\\1', $seed), 0, 8);
} else {
$salt = '';
for ($i = 0; $i < 8; $i ++) {
$salt .= $APRMD5 {
rand(0, 63)
};
}
return $salt;
}
break;
default :
$salt = '';
if ($seed) {
$salt = $seed;
}
return $salt;
break;
}
}
I'm no PHP or Joomla expert but I understand to a certain extent what is going on. I believe as far as an encryption algorithm goes, md5 is being used.
My question is -
What do I need to do to authenticate a un / pw combo against a password stored like this? Presently the salt isn't being stored along with the PW so what do I need to do here exactly? I don't need any code or pseudo-code I just need a clear list of steps to take. If you do feel like providing code I'm writing my application in Java.
EDIT -
Okay I've gotten further supplying the salt / crypto password to the authentication library I'm using however it is saying that they don't matched even after going through all the hasing / decryption. I guess I'll have to play around with this a bit more.
Using that example PW I supplied in the comment below, here's what my java code looks like :
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo("TestUser",
"564c6d2c10a7135fe0ddf0b21d1a1226", getName());
info.setCredentialsSalt(new SimpleByteSource("B9YEkhvnV8pZ8BU7fvVlIVTbEux5N17J"));
return info;
And this is the response I get -
Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - TestUser, rememberMe=false] did not match the expected credentials.
I guess I'm close but I'm still not there. Since we're not passing an algorithm name into the getCryptedPassword PHP function, I'm guessing that it's using the default which appears to be MD5. I wonder why this isn't working.
Thank you,
-Zachary Carter

Try this.
Given a user name $un and a plain text password $pw:
jimport( 'joomla.user.helper' );
$userId = JUserHelper::getUserId( $un );
$user = JUser::getInstance( $userId );
$existingPasswordParts = explode( ':', $user->password );
$salt = $existingPasswordParts[1];
$crypt = JUserHelper::getCryptedPassword( $pw, $salt );
$password = $crypt . ':' . $salt;
if ( $user->password == $password )
{
/* match */
}
The user is fetched, and the used salt is re-used to encrypt the plain text password. After that, both encrypted passwords can be compared against each other.
This should work on J1.6, J1.7 and J2.5.

Joomla was building the hash as plain-text pw + salt but when Shiro is authenticating it builds the hash as salt + plain-text pw. The solution was subclassing SimpleCredentialsMatcher and AbstractHash. I couldn't override the methods in the existing subclasses because they were all protected.

Related

Spreadsheets error " String could not be parsed as XML"

When I try to get all titles of spreadsheets from Google drive, I got this message The string could not be parsed as XML:
ERROR -> SimpleXMLElement::__construct(): Entity: line 1: parser error : Start tag expected, '<' not found in C:\....
ERROR-> SimpleXMLElement::__construct(): { in C:\....
ERROR-> SimpleXMLElement::__construct(): ^ in C:\...
I try to connect on Gooogle drive, which I success, but I need to get the names of spreadsheets on Google drive, I previously use API v3 now I need to use V4.
this is code for call method getSpreadsheets();
$serviceRequest = new DefaultServiceRequest($token->access_token, $token->token_type);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
This is the code of method getSpreadsheets:
public function getSpreadsheets()
{
return new SpreadsheetFeed(
ServiceRequestFactory::getInstance()->get('v4/spreadsheets/1u7WYzJOYMX7uH3AIM70yVLOaHBy8p_uifuJe_Saa2T4?fields=sheets.properties.title')
);
}
And this is SpreadsheetFeed class, where is error causes:
namespace Google\Spreadsheet;
use ArrayIterator;
use SimpleXMLElement;
/**
* Spreadsheet feed.
*
* #package Google
* #subpackage Spreadsheet
* #author Asim Liaquat <asimlqt22#gmail.com>
*/
class SpreadsheetFeed extends ArrayIterator
{
/**
* The spreadsheet feed xml object
*
* #var \SimpleXMLElement
*/
protected $xml;
/**
* Initializes the the spreadsheet feed object
*
* #param string $xml the raw xml string of a spreadsheet feed
*/
public function __construct($xml)
{
$this->xml = new SimpleXMLElement($xml);
$spreadsheets = array();
foreach ($this->xml->entry as $entry) {
$spreadsheets[] = new Spreadsheet($entry);
}
parent::__construct($spreadsheets);
}
/**
* Gets a spreadhseet from the feed by its title. i.e. the name of
* the spreadsheet in google drive. This method will return only the
* first spreadsheet found with the specified title.
*
* #param string $title
*
* #return \Google\Spreadsheet\Spreadsheet|null
*/
public function getByTitle($title)
{
foreach($this->xml->entry as $entry) {
if($entry->title->__toString() == $title) {
return new Spreadsheet($entry);
}
}
return null;
}
}
I try to find a solution how to pass this error!
Any Help, how to solve this error?
Thanks!
This is solution for my app, migrate from v3 to v4 spreadsheets API:
$this->service_drive = new Google_Service_Drive($this->client);
$optParams = array('q'=> 'mimeType="application/vnd.google-apps.spreadsheet"');
$this->files = $this->service_drive->files->listFiles($optParams);
}
// $this->service_drive = new Google_Service_Drive($this->client);
//$optParams = array('q'=> 'mimeType="application/vnd.google-apps.spreadsheet"');
//$this->files = $this->service_drive->files->listFiles($optParams);
//$gdata_spreadsheets=$this->files;//my test
if($this->files !==null){
if (count($this->files->getFiles()) == 0) {
$gdata_spreadsheets=array("No Spreadsheets");
} else {
foreach ($this->files->getFiles() as $file) {
$gdata_spreadsheets[$file->getId()]=$file->getName();
}
}
}
//trenuto ispod code rjesavam
if($gdata->spreadsheet_id != '' && isset( $gdata_spreadsheets[$gdata->spreadsheet_id] ) && $this->files !== null){
$this->service = new Google_Service_Sheets($this->client);
$this->response = $this->service->spreadsheets->get($gdata->spreadsheet_id);
$this->sheets=$this->response->getSheets();
// $spreadsheet = $this->service_drive($gdata_spreadsheets[$gdata->spreadsheet_id]);
// $worksheetFeed = $spreadsheet->getWorksheets();
foreach ( $this->sheets as $sheet ){
$gdata_worksheets[$sheet->properties->sheetId]= $sheet->properties->title;
//$gdata_worksheets[]=$this->sheets;
}
//$gdata_worksheets[]=$gdata->worksheet_id;
if($gdata->worksheet_id != '' && isset( $gdata_worksheets[$gdata->worksheet_id] )){
$range = 'List 2!A1:Z';
$worksheet = $this->service->spreadsheets_values->get($gdata->spreadsheet_id, $range);
$cellFeed = $worksheet->getValues();
foreach( $cellFeed As $row) {
//$row = $cellEntry->getRow();
//$col = $cellEntry;
// $gdata_worksheets=$this->service;
if( $row > 1 ){
$gdata_columns=$row;
break;
}
}
}
}
} catch(Exception $e){
$error = $e->getMessage();
}
This is one part of my code, where is described how to migrate from v3 to v4 spreadsheets API.

Prestashop 1.6 l method

There is an issue with the translations, if the translation is missing prestashop is returining empty string, rather than the key.
Does anyone know the location of the 'l' method used in the controllers?
$this->l('string', 'mod'); //This will output '' if string is not translated.
I want to modify the method and make it return the key if the value is empty, but I cant find it.
I'll assume you are referring to an AdminController, since it's the only one using that function. It uses the function:
protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
{
if ($class === null || $class == 'AdminTab') {
$class = substr(get_class($this), 0, -10);
} elseif (strtolower(substr($class, -10)) == 'controller') {
/* classname has changed, from AdminXXX to AdminXXXController, so we remove 10 characters and we keep same keys */
$class = substr($class, 0, -10);
}
return Translate::getAdminTranslation($string, $class, $addslashes, $htmlentities);
}
In your case it would call Translate::getAdminTranslation('string', 'mod', false, true)
In Translate::getAdminTranslation
We have:
...
$string = preg_replace("/\\\*'/", "\'", $string);
$key = md5($string);
if (isset($_LANGADM[$class.$key])) {
$str = $_LANGADM[$class.$key];
} else {
$str = Translate::getGenericAdminTranslation($string, $key, $_LANGADM);
}
...
Since it won't have the $_LANGADM[$class.$key], it will call:
$str = Translate::getGenericAdminTranslation($string, $key, $_LANGADM);
in your case $str = Translate::getGenericAdminTranslation('string', md5('string'), $_LANGADM);
In there we have:
...
if (isset($lang_array['AdminController'.$key])) {
$str = $lang_array['AdminController'.$key];
} elseif (isset($lang_array['Helper'.$key])) {
$str = $lang_array['Helper'.$key];
} elseif (isset($lang_array['AdminTab'.$key])) {
$str = $lang_array['AdminTab'.$key];
} else {
// note in 1.5, some translations has moved from AdminXX to helper/*.tpl
$str = $string;
}
return $str;
So by default if no key is found, the same string that is trying to be translated is returned. So there is no need to change the function.
On the otherhand, make sure the string it's translated to an empty string. You can also debug these functions to make sure your class is correct, and the file that is storing the corresponding translations doesn't have the empty translation for those strings.

PHP PDO dynamically updating db table with multiple records to a specific user ID

/* Newbie need some help; I am creating a class to auto update my apps db record when instructed to, but I am consistently getting this message below, and for the heck of it, I just not seeing what I am doing wrong. Can someone please look at my codes for me? Thank you.
Warning: PDOStatement::bindParam() expects at least 2 parameters, 1 given in……..on line 331; that where the "else if(is_string($val)){" is located.
*/
// vars given
// DBDriver: MySQL
$myTable = 'seeYou';
$loginDate = NULL;
$ip = $_SERVER['REMOTE_ADDR'];
$date = #date('m/d/Y \a\\t h:i a');
$_id =1;
// data array
$idata = array("last_logged_in"=>$loginDate,
"login_date"=>$date,
"ip_addr"=>$ip
);
class name
{
///------------ other methods here---------///
/**
*--------------------------------------------
* Method - PDO: SET FIELD VALUE PLACEHOLDER
*--------------------------------------------
* #return fields with prefix as placeholder
*/
protected function set_fieldValPlaceHolders(array $data)
{
$set = '';
foreach($data as $field => $value)
{
$set .= $field .'= :'.$field . ',';
}
// remove the last comma
$set = substr($set, 0, -1);
return $set;
}
public function save($data=NULL, $_id = NULL, $rows= NULL, $dbTable= NULL)
{
//----------------- some other codes goes here ----------------//
$id = (int)$_id;
// update row with a specific id
if (isset($id) !== NULL && $rows === NULL)
{
$set = $this->set_fieldValPlaceHolders($data);
$sql = "UPDATE {$dbTable} SET {$set} WHERE user_id = :uid";
try
{
// Build the database statement
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindValue(':uid',$id, PDO::PARAM_INT);
foreach ($data as $field => $val)
{
if(is_int($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_INT');
}
else if(is_string($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_STR');
}
else if(is_bool($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_BOOL');
}
else if(is_null($val)){
$_stmt->bindValue(':'.$field.'\', '.$val="null".', PDO::PARAM_NULL');
}
else {
$_stmt->bindValue(':'.$field.'\', '.$val.', NULL');
}
$result = $_stmt->execute();
$num = $_stmt->rowCount();
}
}
catch(PDOException $e)
{
die('Error! The process failed while updating your record. <br /> Line #'.__LINE__ .' '.$e);
}
if ($result === true)
{
return true;
}
}
Check your bindValue calls: You give 1 parameter (a long string). It needs at least two. Check all the '
for example, it should be:
$_stmt->bindValue(':'.$field, $val, PDO::PARAM_INT);

LDAP on XAMPP localhost

I am using windows XP with XAMPP 1.6.4 - php 5.2.4 with LDAP enabled
trying this script :
$server = "ldap://127.0.0.1/";
$user = "Salman";
$pass = "123";
$con = ldap_connect($server);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
var_dump(ldap_bind($con, $user, $pass));
but ldap_bind always returns this error :
Warning: ldap_bind() [function.ldap-bind]: Unable to bind to server: Can't contact LDAP server in D:\xampp\htdocs\test.php on line 11
bool(false)
Hi i put a class together for this a while back:
<?php
/* USAGE:
* $ldapObj= new Ldap("HOST","PORT","USERNAME","PASSWORD","Distinguished Name"," (mailnickname=USERNAME)",array("*"));
*/
class Ldap {
enter code here
public $ldaphost;
public $ldapport;
public $ldaprdn;
public $ldappass;
public $dn;
public $filter;
public $attributes;
public $ad;
public $ldapbind;
public $ldapresults;
public $ldapentries;
public $ldaperror;
public $ldapstatus;
function __construct($ldaphost, $ldapport, $ldaprdn, $ldappass, $dn, $filter, $attributes) {
$this->ldaphost = $ldaphost;
$this->ldapport = $ldapport;
$this->ldaprdn = $ldaprdn;
$this->ldappass = $ldappass;
$this->dn = $dn;
$this->filter = $filter;
$this->attributes = $attributes;
$this->ad = ldap_connect($this->ldaphost);
if ($this->ad) {
$this->ldapbind = ldap_bind($this->ad, $this->ldaprdn, $this->ldappass);
if ($this->ldapbind) {
$this->ldapresults = ldap_search($this->ad, $this->dn, $this->filter, $this->attributes);
$this->ldapentries = ldap_get_entries($this->ad, $this->ldapresults);
$this->getSid();
$this->ldapstatus = 1;
} else {
$this->ldaperror = "Unable to authenticate user";
$this->ldapstatus = 0;
}
ldap_unbind($this->ad);
} else {
$this->ldaperror = "Could not connect to {$this->ldaphost}";
$this->ldapstatus = 0;
}
}
function getLdapEntry($entry) {
return $this->ldapentries[0][$entry][0];
}
function getLdapEntries() {
return $this->ldapentries;
}
function ldapError() {
return $this->ldaperror;
}
function getSid() {
$sid = "S-";
$entries = $this->ldapentries;
// Convert Bin to Hex and split into byte chunks
$sidinhex = str_split(bin2hex($entries[0]['objectsid'][0]), 2);
// Byte 0 = Revision Level
$sid = $sid . hexdec($sidinhex[0]) . "-";
// Byte 1-7 = 48 Bit Authority
$sid = $sid . hexdec($sidinhex[6] . $sidinhex[5] . $sidinhex[4] . $sidinhex[3] . $sidinhex[2] . $sidinhex[1]);
// Byte 8 count of sub authorities - Get number of sub-authorities
$subauths = hexdec($sidinhex[7]);
//Loop through Sub Authorities
for ($i = 0; $i < $subauths; $i++) {
$start = 8 + (4 * $i);
// X amount of 32Bit (4 Byte) Sub Authorities
$sid = $sid . "-" . hexdec($sidinhex[$start + 3] . $sidinhex[$start + 2] . $sidinhex[$start + 1] . $sidinhex[$start]);
}
$this->sid = $sid;
}
}
?>

how to edit .htpasswd using php?

i have a protected directory where only user on .htpasswd can access, but sometimes it requires the user to change password or username, edit a specific username password to his username him self
sample users
kevien : kka
mike : mike
And let say i want to change kevien to XYZ
And same thing goes to password
I have modified function to use all types of crypt alghoritms. Someone may find it useful:
/*
Function change password in htpasswd.
Arguments:
$user > User name we want to change password to.
$newpass > New password
$type > Type of cryptogrphy: DES, SHA, MD5.
$salt > Option: Add your custom salt (hashing string).
Salt is applied to DES and MD5 and must be in range 0-9A-Za-z
$oldpass > Option: Add more security, user must known old password to change it.
This option is not supported for DES and MD5 without salt!!!
$path > Path to .htaccess file which contain the password protection.
Path to password file is obtained from this .htaccess file.
*/
function changePass($user, $newpass, $type="SHA", $salt="", $oldpass="", $path=".htaccess")
{
switch ($type) {
case "DES" :
$salt = substr($salt,0,2); // Salt must be 2 char range 0-9A-Za-z
$newpass = crypt($newpass,$salt);
if ($oldpass != null) {
$oldpass = crypt($oldpass,$salt);
}
break;
case "SHA" :
$newpass = '{SHA}'.base64_encode(sha1($newpass, TRUE));
if ($oldpass != null) {
$oldpass = '{SHA}'.base64_encode(sha1($oldpass, TRUE));
}
break;
case "MD5" :
$salt = substr($salt,0,8); //Salt must be max 8 char range 0-9A-Za-z
$newpass = crypt_apr1_md5($newpass, $salt);
if ($oldpass != null) {
$oldpass = crypt_apr1_md5($oldpass, $salt);
}
break;
default:
return false;
break;
}
$hta_arr = explode("\n", file_get_contents($path));
foreach ($hta_arr as $line) {
$line = preg_replace('/\s+/','',$line); // remove spaces
if ($line) {
$line_arr = explode('"', $line);
if (strcmp($line_arr[0],"AuthUserFile") == 0) {
$path_htaccess = $line_arr[1];
}
}
}
$htp_arr = explode("\n", file_get_contents($path_htaccess));
$new_file = "";
foreach ($htp_arr as $line) {
$line = preg_replace('/\s+/', '', $line); // remove spaces
if ($line) {
list($usr, $pass) = explode(":", $line, 2);
if (strcmp($user, $usr) == 0) {
if ($oldpass != null) {
if ($oldpass == $pass) {
$new_file .= $user.':'.$newpass."\n";
} else {
return false;
}
} else {
$new_file .= $user.':'.$newpass."\n";
}
} else {
$new_file .= $user.':'.$pass."\n";
}
}
}
$f = fopen($path_htaccess,"w") or die("couldn't open the file");
fwrite($f, $new_file);
fclose($f);
return true;
}
Function for generating Apache like MD5:
/**
* #param string $password
* #param string|null $salt
* #ref https://stackoverflow.com/a/8786956
*/
function crypt_apr1_md5($password, $salt = null)
{
if (!$salt) {
$salt = substr(base_convert(bin2hex(random_bytes(6)), 16, 36), 1, 8);
}
$len = strlen($password);
$text = $password . '$apr1$' . $salt;
$bin = pack("H32", md5($password . $salt . $password));
for ($i = $len; $i > 0; $i -= 16) {
$text .= substr($bin, 0, min(16, $i));
}
for ($i = $len; $i > 0; $i >>= 1) {
$text .= ($i & 1) ? chr(0) : $password[0];
}
$bin = pack("H32", md5($text));
for ($i = 0; $i < 1000; $i++) {
$new = ($i & 1) ? $password : $bin;
if ($i % 3) {
$new .= $salt;
}
if ($i % 7) {
$new .= $password;
}
$new .= ($i & 1) ? $bin : $password;
$bin = pack("H32", md5($new));
}
$tmp = '';
for ($i = 0; $i < 5; $i++) {
$k = $i + 6;
$j = $i + 12;
if ($j == 16) {
$j = 5;
}
$tmp = $bin[$i] . $bin[$k] . $bin[$j] . $tmp;
}
$tmp = chr(0) . chr(0) . $bin[11] . $tmp;
$tmp = strtr(
strrev(substr(base64_encode($tmp), 2)),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
);
return "$" . "apr1" . "$" . $salt . "$" . $tmp;
}
Demo of crypt_apr1_md5() is available here.
Note that as of Apache 2.4, bcrypt is supported, so you can (and SHOULD) just use password_hash() on newer versions of Apache for this purpose.
Ofc this is just a sample, that will read your current file, find the given username and change either it is password of username.
Please keep in mind that this code is not safe and you would still need to parse the username and password so it does not break your file.
$username = $_POST['user'];
$password = $_POST['pass'];
$new_username = $_POST['newuser'];
$new_password = $_POST['newpass'];
$action = $_POST['action'];
//read the file into an array
$lines = explode("\n", file_get_contents('.htpasswd'));
//read the array and change the data if found
$new_file = "";
foreach($lines as $line)
{
$line = preg_replace('/\s+/','',$line); // remove spaces
if ($line) {
list($user, $pass) = split(":", $line, 2);
if ($user == $username) {
if ($action == "password") {
$new_file .= $user.':'.$new_password."\n";
} else {
$new_file .= $new_username.':'.$pass."\n";
}
} else {
$new_file .= $user.':'.$pass."\n";
}
}
}
//save the information
$f=fopen(".htpasswd","w") or die("couldn't open the file");
fwrite($f,$new_file);
fclose($f);
Don't. Store your authdb in a database instead, via e.g. mod_auth_mysql.
Googled "php generate htpasswd", got this article: How to create a password for a .htpasswd file using PHP.
The key line seems to be:
$password = crypt($clearTextPassword, base64_encode($clearTextPassword));
So I imagine you'd read in the file contents with file_get_contents, parse it into an associative array, modify the relevant entries (encrypting the password as shown above), write the array back into a string, and use file_put_contents to write the file back out.
This is most definitely not standard practice, however. Sounds like the job for a database. If you feel weird about setting up a whole database server, and your host supports it, SQLite might be a good choice.
Just in case someone is just looking for a working script, here is a solution.
It is the script published here by Kavoir with a minor change: http://www.kavoir.com/backyard/showthread.php?28-Use-PHP-to-generate-edit-and-update-htpasswd-and-htgroup-authentication-files
<?php
/*
$pairs = array(
'username' = 'password',
);
*/
// Algorithm: SHA1
class Htpasswd {
private $file = '';
public function __construct($file) {
if (file_exists($file)) {
$this -> file = $file;
} else {
return false;
}
}
private function write($pairs = array()) {
$str = '';
foreach ($pairs as $username => $password) {
$str .= "$username:{SHA}$password\n";
}
file_put_contents($this -> file, $str);
}
private function read() {
$pairs = array();
$fh = fopen($this -> file, 'r');
while (!feof($fh)) {
$pair_str = str_replace("\n", '', fgets($fh));
$pair_array = explode(':{SHA}', $pair_str);
if (count($pair_array) == 2) {
$pairs[$pair_array[0]] = $pair_array[1];
}
}
return $pairs;
}
public function addUser($username = '', $clear_password = '') {
if (!empty($username) && !empty($clear_password)) {
$all = $this -> read();
// if (!array_key_exists($username, $all)) {
$all[$username] = $this -> getHash($clear_password);
$this -> write($all);
// }
} else {
return false;
}
}
public function deleteUser($username = '') {
$all = $this -> read();
if (array_key_exists($username, $all)) {
unset($all[$username]);
$this -> write($all);
} else {
return false;
}
}
public function doesUserExist($username = '') {
$all = $this -> read();
if (array_key_exists($username, $all)) {
return true;
} else {
return false;
}
}
private function getHash($clear_password = '') {
if (!empty($clear_password)) {
return base64_encode(sha1($clear_password, true));
} else {
return false;
}
}
}
You can use this script like:
$htp = new Htpasswd('.htpasswd');
$htp -> addUser('username1', 'clearpassword1'); // this will add or edit the user
$htp -> deleteUser('username1');
// check if a certain username exists
if ($htp -> doesUserExist('username1')) {
// user exists
}