This topic is locked

Hash existing passwords using BCRYPT algorithm

11/14/2023 11:22:26 AM
PHPRunner Tips and Tricks
admin

If for any reason you are still using plain text passwords in your database, it is the time to switch to a reliable hashing mechanim like BCRYPT. Here is how you can make this switch in PHPRunner applications.

  1. Make sure your password field is long enough to store hashed passwords. We recommend a text field 100 characters long.
  2. Create a backup of your login table. In MySQL this can be as simple as SELECT * INTO mytable_backup FROM mytable
  3. Save PHP code below to a file named bcrypt.php and save it to the folder where your web application resides.
  4. Change the following variables:

$table = ""; // login table name
$bcryprt_field = ""; // password field name
$keyfield = ""; // login table key column name
$cnt = 100; // display progress after each 100 records
  1. Run the script as https://yourwebsite.com/project/bcrypt.php
  2. Rebuild the project and upload to the website.

PHP code:

<?php
@ini_set("display_errors","1");
include_once("include\dbcommon.php");

$table = "";
$bcryprt_field = "";
$keyfield = "";
$cnt = 100;

set_time_limit(100000);

if(postvalue("a") != "bcrypt"){
echo "<script type='text/javascript' src='include/jquery.js?41242'></script>";
echo "<div id='currStep'>Start...</div>";
echo "<script>
window.curcount = 0;
window.totalcount = 0;
startSending();

function startSending(){
$.post('bcrypt.php',{
step: window.curcount,
a: 'bcrypt'
})
.done(function(sendingMessagesInstep){
if(sendingMessagesInstep == 'error'){
$('#currStep').html('Not all data is exists');
return false;
}
window.totalcount+=parseInt(sendingMessagesInstep);
if (sendingMessagesInstep == ".$cnt.") {
window.curcount++;
$('#currStep').html((window.curcount * ".$cnt.")+' records processed');
startSending();
} else {
$('#currStep').html('Total processed '+window.totalcount+' records');
window.curcount = 0;
window.totalcount = 0;
};
});
}

</script>";
}

if(postvalue("a") == "bcrypt"){
if(!$table || !$bcryprt_field || !$keyfield || !$cnt){
echo "error";
exit();
}
$step = intval(postvalue("step"));
$rs = DB::Select($table);
$i=0;
$resutl = 0;
while($data = $rs->fetchAssoc()){
if($i >= $step*$cnt && $i < ($step+1)*$cnt){
$value = $data[$bcryprt_field];
if(!isBcryptHash($value)){
$newvalue = getPasswordHash($value);
DB::Update($table, array($bcryprt_field=>$newvalue), array($keyfield=>$data[$keyfield]));
}
$resutl++;
}
if($i >= ($step+1)*$cnt)
break;
$i++;
}
echo $resutl;
exit();
}

function isBcryptHash( $password ) {
if(strlen($password) === 0)
return true;
$pwdParts = explode( '$', $password);
if( count( $pwdParts ) !== 4 ) {
return false;
}
if( $pwdParts[0] !== '' ) {
return false;
}
if( !in_array( $pwdParts[1], array("2a","2b","2y","2x") )) {
return false;
}
if(!is_numeric( $pwdParts[2] ) || $pwdParts[2] < 1 ) {
return false;
}
if( strlen( $pwdParts[3]) !== 53 ) {
return false;
}
return true;
}
?>