Symfony2: How do i generate sha512 hash of a password?
-
27-05-2021 - |
문제
I need to compare the password entered by the user if it is valid or not. How do i get the sha512 encryption. I am also using FOSUserBundle in my project.
해결책
In your controller you can do (assuming that you set sha512 as encoding algorithm in app/config/security.yml
)
$userName = 'username';
$password = "pass";
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->loadUserByUsername($userName);
$encoder = $this->get('security.encoder_factory')->getEncoder($user);
$encodedPass = $encoder->encodePassword($password, $user->getSalt());
echo $user->getPassword() === $encodedPass;
다른 팁
Symfony has several different ways to store passwords. The logic to hash and check the password is stored in several "Encoder" classes:
Which one is used can be configured in security.yml, under the key encoder
. If this says sha512
, you are using the MessageDigestPasswordEncoder
.
The encoder type can be different for different user types. To get the correct encoder for a user, you can ask the EncoderFactory. This is already done for you in the UserPasswordEncoder: you pass a user and a plain password to UserPasswordEncoder->isPasswordValid
, and it checks the password with the correct encoder belonging to this user. This is the easiest interface to check a user's password.
If you really want to know how the SHA512 hashing works, you can check MessageDigestPasswordEncoder. It combines the salt and password in a string like "password{salt}". It computes the hash of this string 5000 times. This is to make the password hash slow, so it is not easy to brute-force.
When checking whether the password is valid, it uses hash_equals
. This is a constant-time comparison, which prevents timing attacks on the password hash.
If you're sure it's SHA512 you need, try this.