Skip to content

Instantly share code, notes, and snippets.

@nielsiano

nielsiano/shaToBcrypt.php

Last active Dec 19, 2015
Embed
What would you like to do?
Ion_Auth: Change password from sha1+salt to bcrypt
<?php
/**
* Check if string is sha1
*
* @return bool
* @author Nielsiano
**/
public function is_sha1($password)
{
return preg_match('/^[a-z0-9]{40}$/i', $password);
}
/**
* Change password from sha1+salt to bcrypt
* Used for migrating and logging in user
* @return bool
* @author Nielsiano
**/
public function hash_password_db_migrate($id, $password)
{
// first, get the hash from DB matching the $id
$query = $this->db->select('password, salt')
->where('id', $id)
->limit(1)
->get($this->tables['users']);
$hash_password_db = $query->row();
if ($query->num_rows() !== 1)
{
return FALSE;
}
// if password hash from DB is sha1
if ($this->is_sha1($hash_password_db->password))
{
// validate the sha1 hash password from hash_password_db method
if ($this->hash_password_db($id, $password, $use_sha1_override=TRUE))
{
// Hash the user input using bcrypt
$new_bcrypt_password = $this->hash_password($password, FALSE);
// Update the [password] from sha1 to the new bcrypt in db
$data = array(
'password' => $new_bcrypt_password
);
$this->db->where('id', $id);
$this->db->update($this->tables['users'], $data);
// login
return TRUE;
}
}
// validate using bcrypt since sha1 hash didnt exist in db
elseif ($this->hash_password_db($id, $password))
{
// login
return TRUE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment