user3125255
user3125255

Reputation: 41

Symfony2 How to use encode password (not for security)

I'm trying to create an advert system.

class Advert {

    protected $password;

}

To have access, a user should give the password of his advert, not his password account. But how can the Symfony2 security framework be used to encode and check the password?

Upvotes: 3

Views: 14089

Answers (2)

DarkLeafyGreen
DarkLeafyGreen

Reputation: 70466

Create a password encoder/decoder service:

namespace Acme\TestBundle\Service;

use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;

class Sha256Salted implements PasswordEncoderInterface
{

    public function encodePassword($raw, $salt)
    {
        return hash('sha256', $salt . $raw); // Custom function for encrypt with sha256
    }

    public function isPasswordValid($encoded, $raw, $salt)
    {
        return $encoded === $this->encodePassword($raw, $salt);
    }

}

This is how you would use it:

$advert->setSalt(uniqid(mt_rand())); // Unique salt

// Set encrypted password
$encoder = $this->container->get('acme.test.sha256salted_encoder')
  ->getEncoder($advert);
$password = $encoder->encodePassword('MyPass', $advert->getSalt());
$advert->setPassword($password);

Taken from: Symfony2 create own encoder for storing password

Upvotes: 3

Lebnik
Lebnik

Reputation: 636

In Symfony 2.6 and may be in less versions:

$user = new User();// you object \Acme\DemoBundle\Entity\User from database

$hash = $this->get('security.password_encoder')->encodePassword($user, 'user password');

$user->setPassword($hash);

if( $this->get('security.password_encoder')->isPasswordValid($user, 'user password') ){
    echo 'password equal';
}

Upvotes: 6

Related Questions