Symfony2 create own encoder for storing password

Solution 1:

To make it simple: you have to create and add a new Service, add it to your bundle and specity that the User class will use it. First you have to implement your own password encoder:

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 password encrypt
    }

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

}

Then you'll add the service definition and you want to specify to use your custom encoder for the class User. In TestBundle/Resources/config/services.yml you add custom encoder:

services:
    sha256salted_encoder:
        class: Acme\TestBundle\Service\Sha256Salted

and in app/config/security.yml you can therefore specify your custom class as default encoder (for Acme\TestBundle\Entity\User class):

 encoders:
   Acme\TestBundle\Entity\User:
     id: acme.test.sha256salted_encoder

Of course, salt plays a central role in password encryption. Salt is unique and is stored for each user. The class User can be auto-generated using YAML annotations (table should - of course - contain fields username, password, salt and so on) and should implement UserInterface.

Finally you can use it (controller code) when you have to create a new Acme\TestBundle\Entity\User:

// Add a new User
$user = new User();
$user->setUsername = 'username';
$user->setSalt(uniqid(mt_rand())); // Unique salt for user

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

Solution 2:

Thank you gremo, There's a small problem in the last snippet of your code, when using the service we should put it's name "sha256salted_encoder" and not acme.test.sha256salted_encoder. in addition

// Add a new User
$user = new User();
$user->setUsername = 'username';
$user->setSalt(uniqid(mt_rand())); // Unique salt for user

// Set encrypted password
$encoder = $this->container->get('security.encoder_factory')
  ->getEncoder($user);
$password = $encoder->encodePassword('MyPass', $user->getSalt());
$user->setPassword($password);

first of all we will call the security encoder, then we will find

sha256salted_encoder

and the service will be useful.

All the best