Tuesday, June 23, 2009

Symfony: password hashing and login

It's a good practice not to keep the clear values of the passwords in the db, but to store only their hash values.
You can do login operations comparing the hash value of the inserted password with the stored hash value.

How to do it with Symfony 1.2, propel ORM, MD5 hashing:
  • db schema: Use a VARCHAR, length must be at least 32
  • validator:
    - require a minimum length (ex: 3 chars) or (better) regexp validation
    - use a widget Schema password
    $this->widgetSchema['password'] = new sfWidgetFormInputPassword (array(
    'always_render_empty' => false, //IMPORTANT !!
    ));
  • model: modify the method setPassword($v) assigning the md5 value:
    public function setPassword($v)
    //set md5 password if there is a new inserted password
    if (strlen($v)!=32) //if is not a md5 value, convert into it (*)
    $v = md5($v);
    return
    parent::setPassword($v); }
  • To check the login data, use the md5 value in the post action :
    $criteria->add(UsersPeer::USER,$request->getParameter('user'))
    ->
    add(UsersPeer::PASSWORD,md5($request->getParameter('passwordlogin')));
From now, only the hash value of the passwords will be stored.
The CRUD operations will work.

(*) Note: it won't work if the clear password is 32 chars length.

1 comment:

  1. shouldn't use md5 anymore, google "md5 cracked" for reasons

    ReplyDelete

 

PHP and tips|PHP