Php - Password hashing - php

I've made this password class as you can see below:
<?php
namespace lib\Api;
class Password{
private $password;
private $salt;
private $hash;
public function __construct($password,$salt = ""){
$this->password = $password;
$this->salt = $salt;
$this->generateHash($this->password,$this->salt);
}
public function generateHash($password,$salt = ""){
$this->hash = hash('sha256',$password.$salt);
return $this->hash;
}
public function get(){
return $this->hash;
}
public function equals($password){
if($this->hash == $password){
return true;
}
return false;
}
}
?>
So i use this to register a user in a user.php file/class
$this->password = (new Password($password,$this->getSalt()))->get();
, i also use this too again check this in a login.php file/class
if((new Password($this->password,$salt))->equals($password)){
return true;
}
return false;
. Now i know that if you hash something that it depends in wich file it is, how it hashes the value. In this partical case it confuses me very much, as i both officialy hash it in the password.php file/class. How does this work and how can i solve it easily and nicely?

It's hard to understand what you're asking, but I bet you want to hash the value of $password before you check it's equality.
<?php
namespace lib\Api;
class Password{
private $password;
private $salt;
private $hash;
public function __construct($password,$salt = ""){
$this->password = $password;
$this->salt = $salt;
$this->hash = $this->generateHash($this->password);
}
public function generateHash($password){
return hash('sha256',$password.$this->salt);
}
public function get(){
return $this->hash;
}
public function equals($password){
if($this->hash == $this->generateHash($password){
return true;
}
return false;
}
}

Related

Where to include the private key in the ds_config.ini file (PHP)

I'm new to the docusign API.
I already did the quick start: "Quick start: request a signature via your application (integrated signature)".
Now I'm blocked for the PHP construction part: "JSON Web Token (JWT) Grant".
I created the JWT token, and now I don't understand where I should include the rsa private key in the ds_config.ini file
private $config;
private static $instance;
private static function getInstance() {
if(is_null(self::$instance)){
self::$instance = new DSConfig();
}
return self::$instance;
}
public function __construct() {
date_default_timezone_set('UTC');
$clientId = getenv("DS_CLIENT_ID");
if (!is_null($clientId) and !empty($clientId)) {
$this->config["DS_CLIENT_ID"] = $clientId;
$this->config["DS_AUTH_SERVER"] = getenv("DS_AUTH_SERVER");
$this->config["DS_IMPERSONATED_USER_GUID"] = getenv("DS_IMPERSONATED_USER_GUID");
$this->config["DS_TARGET_ACCOUNT_ID"] = getenv("DS_TARGET_ACCOUNT_ID");
$this->config["SIGNER_EMAIL"] = getenv("SIGNER_EMAIL");
$this->config["SIGNER_NAME"] = getenv("SIGNER_NAME");
$this->config["CC_EMAIL"] = getenv("CC_EMAIL");
$this->config["CC_NAME"] = getenv("CC_NAME");
$this->config["DS_PRIVATE_KEY"] = getenv("DS_PRIVATE_KEY");
} else {
$this->config = parse_ini_file('ds_config.ini', true);
}
}
private function _auth_server() {
return $this->config["DS_AUTH_SERVER"];
}
public static function auth_server() {
return self::getInstance()->_auth_server();
}
private function _client_id() {
return $this->config["DS_CLIENT_ID"];
}
public static function client_id() {
return self::getInstance()->_client_id();
}
private function _impersonated_user_guid() {
return $this->config["DS_IMPERSONATED_USER_GUID"];
}
public static function impersonated_user_guid() {
return self::getInstance()->_impersonated_user_guid();
}
private function _target_account_id() {
return $this->config["DS_TARGET_ACCOUNT_ID"];
}
public static function target_account_id(){
return self::getInstance()->_target_account_id();
}
private function _signer_email() {
return $this->config["SIGNER_EMAIL"];
}
public static function signer_email(){
return self::getInstance()->_signer_email();
}
private function _signer_name(){
return $this->config["SIGNER_NAME"];
}
public static function signer_name(){
return self::getInstance()->_signer_name();
}
private function _cc_email() {
return $this->config["CC_EMAIL"];
}
public static function cc_email(){
return self::getInstance()->_cc_email();
}
private function _cc_name(){
return $this->config["CC_NAME"];
}
public static function cc_name(){
return self::getInstance()->_cc_name();
}
private function _private_key() {
return $this->config["DS_PRIVATE_KEY"];
}
public static function private_key(){
return self::getInstance()->_private_key();
}
public static function aud() {
$auth_server = self::getInstance()->_auth_server();
if (strpos($auth_server, 'https://') !== false) {
$aud = substr($auth_server, 8);
} else { # assuming http://blah
$aud = substr($auth_server, 7);
}
return $aud;
}
public static function api() {
return "restapi/v2";
}
public static function jwt_scope() {
return "signature";
}
Thanks for your help
Store the private key in the ds_config.ini file. In the ds_config.ini file, add the private key, including the BEGIN / END lines with a pair of quotation marks. Example:
DS_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAkbz3bi31zrH2ry4p8S4ncPoMdkUyu+MG46m9BalOKzWNNAvW
1LVs5ftlXxzA6V0m6nx895w8S761/qZ8xtAAl99DezRn/3CueeBUyw+tvlmEBu1C
....
UC1WqwKBgQCY/6aZxlWX9XYgsQsnUjhj2aTwr7pCiQuYceIzLTQzy+nz8M4PfCE1
rjRsm6YTpoxh7nuW2qnFfMA58UPs9tonN/z1pr9mKfwmamtPXeMSJeEZUVmh7mNx
PEHgznlGh/vUboCuA4tQOcKytxFfKG4F+jM/g4GH9z46KZOow3Hb6g==
-----END RSA PRIVATE KEY-----"
You can find more details with an example here

PHP error printing inside class

I'm trying to play with a class and not understand how it works. Some people explained how to pass variables between a function. My problem at the moment is errors. And how to extract errors from the class and print to the screen. My output is username only. How to get errors?
class form
{
protected $username;
protected $password;
protected $errors = array();
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
public function get_errors()
{
return $this->errors;
}
public function getPassword(){
return $this->password;
}
public function getUserName() {
return $this->username;
return $this->errors = "No MySQL connection.";
}
}
$test = new form('name1', 'passw2');
echo $test->getUserName();
You can not return two time inside a function. But you can achieve what you want like below:-
public function getUserName() {
$this->errors = "No MySQL connection.";
return $this->username.'<br/>'.$this->errors;
}
Note:- this is the solution but your code have no mean. You have to do some useful stuff
try throw exception
public function getUserName() {
if($this->errors) {
throw new Exception($this->errors);
}
return $this->username;
}
$test = new form('name1', 'passw2');
try {
echo $test->getUserName();
} catch(Exception $error) {
echo 'Error:'.$error->getMessage();
}
If you get error you can simple catching this error and output to web,console or error log;
class form
{
protected $username;
protected $password;
protected $errors = array();
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
public function getErrors()
{
return $this->errors;
}
public function getPassword()
{
return $this->password;
}
public function getUserName()
{
/* Add some an error to an error's array */
$this->errors[] = "No MySQL connection.";
return $this->username;
}
}
$test = new form('name1', 'passw2');
echo $test->getUserName();
var_dump($test->getErrors()); /* Get errors from a class */

PHP class return nothing

I'm just beginner with PHP OOP. I have a class and output is empty:
$test = new form('name1', 'passw2');
$test->getName();
and class:
<?php
class form
{
protected $username;
protected $password;
protected $errors = array();
function _construct($username, $password){
$this->username=$username;
$this->password=$password;
}
public function getsomething() {
echo '<br>working'. $this->getn() . '<-missed';
}
public function getName(){
return $this->getsomething();
}
public function getn() {
return $this->username;
}
}
?>
And output is only text without username:
POST working
working<-missed
Where is name1?
I've modifed your code a bit and added some examples to play around with.
This should get you started.
class form
{
protected $username;
protected $password;
protected $errors = array();
// construct is a magic function, two underscores are needed here
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
// functions starting with get are called Getters
// they are accessor functions for the class property of the same name
public function getPassword(){
return $this->password;
}
public function getUserName() {
return $this->username;
}
public function render() {
echo '<br>working:';
echo '<br>Name: ' . $this->username; // using properties directly
echo '<br>Password:' . $this->password; // not the getters
}
}
$test = new form('name1', 'passw2');
// output via property access
echo $test->username;
echo $test->password;
// output via getter methods
echo $test->getUserName();
echo $test->getPassword();
// output via the render function of the class
$test->render();
Hi You have used _construct it should be __contrust(2 underscores)

How can use setstate in Yii

I want create random session after successful sign in and destroy it after log out.
How can do it? I used $this->user->setState
I added this code
class UserIdentity extends CUserIdentity {
protected $_id;
public function authenticate(){
$user = User::model()->find('LOWER(username)=?', array(strtolower($this->username)));
if(($user===null) || ($this->password!==$user->password)) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
} else {
$this->_id = $user->id;
$this->username = $user->username;
$this->user->setState('random',Yii::app()->user->random);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId(){
return $this->_id;
}
}
Use $this->setState instead of $this->user->setState

login class returning bol(false)

I have the fallowing class that I have written for a login application using this tutorial :
class passHash{
private static $algo='$2y$';
private static $cost ='12$';
private function generateSalt(){
$salt=substr(sha1(mt_rand()),0,22);
return $salt;
}
public function hashPassword($password){
$hashpassword=crypt($password,self::$algo.self::$cost.self::generateSalt());
return $hashpassword;
}
public function checkPassword($hash, $password){
$fullsalt=substr($hash,0,29);
$newhash=crypt($password,$fullsalt);
if ($newhash==$password){
return true;
}else{
return false;
}
}
}
I think the code is self explanatory and i saw that there are a lot of questions regarding this login class.
Now the problem that i have encountered is with checking the password. If I do something like:
$a=passHash::hashPassword('1234');
$b=passHash::checkPassword($a,'1234');
var_dump($b);
I gate the result of bool(false)
Where is the problem with this code ?
EDIT 1
if I modifay the checkPassword like this:
public function checkPassword($hash, $password){
$fullsalt=substr($hash,0,29);
$newhash=crypt($password,$fullsalt).'<br>';
return $newhash;
}
and then i do :
$a=passHash::hashPassword('1234');
echo 'hashPassword: '.$a.'<br>';
$b=passHash::checkPassword($a,'1234');
echo 'checkPassword: '.$b.'<br>';
i get
hashPassword:$2y$12$6e29c2bbdacad854b1a63O8aty2a/.MQN0wbdmClnhXMbH3/tfQfG
checkPassword: $2y$12$6e29c2bbdacad854b1a63O8aty2a/.MQN0wbdmClnhXMbH3/tfQfG
they are identical .. so where is the problem ?
The test should be this:
if ($newhash==$hash){
return true;
}else{
return false;
}
the full working code is:
class passHash{
private static $algo='$2y$';
private static $cost ='12$';
private function generateSalt(){
$salt=substr(sha1(mt_rand()),0,22);
return $salt;
}
/**
#param string $password
*/
public function hashPassword($password){
$hashpassword=crypt($password,self::$algo.self::$cost.self::generateSalt());
return $hashpassword;
}
/**
* #param string $hashpassword
* #param string $password
*/
public function checkPassword($hashpassword, $password){
$fullsalt=substr($hashpassword,0,29);
$newhash=crypt($password,$fullsalt);
return ($newhash==$hashpassword);
}
}

Categories