Hash and salt password php

Safe Password Hashing

This section explains the reasons behind using hashing functions to secure passwords, as well as how to do so effectively.

Password hashing is one of the most basic security considerations that must be made when designing any application that accepts passwords from users. Without hashing, any passwords that are stored in your application’s database can be stolen if the database is compromised, and then immediately used to compromise not only your application, but also the accounts of your users on other services, if they do not use unique passwords.

By applying a hashing algorithm to your user’s passwords before storing them in your database, you make it implausible for any attacker to determine the original password, while still being able to compare the resulting hash to the original password in the future.

It is important to note, however, that hashing passwords only protects them from being compromised in your data store, but does not necessarily protect them from being intercepted by malicious code injected into your application itself.

Why are common hashing functions such as md5() and sha1() unsuitable for passwords?

Hashing algorithms such as MD5, SHA1 and SHA256 are designed to be very fast and efficient. With modern techniques and computer equipment, it has become trivial to «brute force» the output of these algorithms, in order to determine the original input.

Because of how quickly a modern computer can «reverse» these hashing algorithms, many security professionals strongly suggest against their use for password hashing.

How should I hash my passwords, if the common hash functions are not suitable?

When hashing passwords, the two most important considerations are the computational expense, and the salt. The more computationally expensive the hashing algorithm, the longer it will take to brute force its output.

PHP provides a native password hashing API that safely handles both hashing and verifying passwords in a secure manner.

Читайте также:  Python scipy optimize curve fit

Another option is the crypt() function, which supports several hashing algorithms. When using this function, you are guaranteed that the algorithm you select is available, as PHP contains native implementations of each supported algorithm, in case one or more are not supported by your system.

The suggested algorithm to use when hashing passwords is Blowfish, which is also the default used by the password hashing API, as it is significantly more computationally expensive than MD5 or SHA1, while still being scalable.

Note that if you are using crypt() to verify a password, you will need to take care to prevent timing attacks by using a constant time string comparison. Neither PHP’s == and === operators nor strcmp() perform constant time string comparisons. As password_verify() will do this for you, you are strongly encouraged to use the native password hashing API whenever possible.

What is a salt?

A cryptographic salt is data which is applied during the hashing process in order to eliminate the possibility of the output being looked up in a list of pre-calculated pairs of hashes and their input, known as a rainbow table.

In more simple terms, a salt is a bit of additional data which makes your hashes significantly more difficult to crack. There are a number of services online which provide extensive lists of pre-computed hashes, as well as the original input for those hashes. The use of a salt makes it implausible or impossible to find the resulting hash in one of these lists.

password_hash() will create a random salt if one isn’t provided, and this is generally the easiest and most secure approach.

How do I store my salts?

When using password_hash() or crypt() , the return value includes the salt as part of the generated hash. This value should be stored verbatim in your database, as it includes information about the hash function that was used and can then be given directly to password_verify() or crypt() when verifying passwords.

The following diagram shows the format of a return value from crypt() or password_hash() . As you can see, they are self-contained, with all the information on the algorithm and salt required for future password verification.

Читайте также:  Template tpl php drupal

Источник

Хэширование паролей в PHP 5.5 с использованием нового API

Использование BCrypt является общепринятым и лучшим способом для хэширования паролей, но большое количество разработчиков по-прежнему используют старые и слабые алгоритмы, вроде MD5 и SHA1. Некоторые разработчики даже не используют соль для хэширования. Новый API хэширования в PHP 5.5 ставит своей целью привлечь внимание к BCrypt, упрощая работу с ним. В этой статье я расскажу об основах использования нового API для хеширования в PHP.

  • password_hash() — используется для хэширования пароля.
  • password_verify() — используется для проверки пароля на соответствие хэшу.
  • password_needs_rehash() — используется для проверки необходимости создать новый хэш.
  • password_get_info() — возвращает имя алгоритма хеширования и различные параметры, используемые при хэшировании.

password_hash()

Хотя функция crypt() довольно безопасна, она, по мнению многих, слишком сложная. Некоторые разработчики, чтобы не возиться с ней, используют слабую соль и слабый алгоритм для генерирования хэша, например:

Но функция password_hash() позволяет упростить нашу жизнь и обезопасить наш код. Когда вам нужно получить хэш пароля, просто скормите его в эту функцию, и она вернет хэш, который можно хранить в базе данных.

Вот и все! Первым параметром является строка пароля, который необходимо захэшировать, а второй параметр определяет алгоритм, который должен быть использован для генерирования хэша.

Алгоритм по умолчанию, в настоящее время, BCrypt, но более сильный алгоритм может быть установлен по умолчанию, когда-нибудь в будущем, и, возможно, он будет генерировать большие строки. Если вы используете PASSWORD_DEFAULT в ваших проектах, обязательно храните хэш в колонке, размером больше 60 символов. Установка размера колонки до 255 может быть хорошим выбором. Вы также можете использовать PASSWORD_BCRYPT в качестве второго параметра. В этом случае результат всегда будет 60 символов.

Главное здесь в том, что вам не нужно заботиться о значении соли и стоимости вычисления хэша. Новый API будет делать это за вас. И соль является частью хэша, так что вам не придется хранить его отдельно. Если вы хотите использовать вашу собственную соль (или стоимость вычисления), вы можете сделать это путем передачи третьего аргумента функции:

 custom_function_for_salt(), //write your own code to generate a suitable salt 'cost' => 12 // the default cost is 10 ]; $hash = password_hash($password, PASSWORD_DEFAULT, $options); 

Таким образом, Вы будете всегда идти в ногу с актуальными мерами безопасности. Если PHP позже примет решение о применении более мощного алгоритма хеширования, ваш код может воспользоваться им без изменений.

Читайте также:  Css inline style float

password_verify()

Теперь, когда вы видели, как генерировать хэши с новым API, давайте посмотрим, как проверить пароль. Мы просто берем хэш из базы, и пароль, введенный пользователем и передаем их в эту функцию. password_verify() возвращает true, если хэш соответствует указанному паролю.

Соль является частью хэша и именно поэтому нам не придется возиться с ней отдельно.

password_needs_rehash()

Что делать, если вам нужно изменить соль или стоимость вычисления для сохраненных паролей? Например, вы решили усилить безопасность и увеличить стоимость вычисления или изменить соль. Или PHP изменил алгоритм хэширования, используемый по умолчанию. В этих случаях вы хотели бы изменить существующие хэши паролей. Функция password_needs_rehash() проверяет, использует ли хэш пароля конкретный алгоритм, соль и стоимость вычисления.

 12])) < // the password needs to be rehashed as it was not generated with // the current default algorithm or not created with the cost // parameter 12 $hash = password_hash($password, PASSWORD_DEFAULT, ['cost' =>12]); // don't forget to store the new hash! > 

Имейте в виду, что вам нужно сделать это, когда пользователь авторизуется на сайте, так как это единственный раз, когда у вас есть доступ к его незашифрованному паролю.

password_get_info()

  • algo — константа, которая идентифицирует конкретный алгоритм
  • algoName — название используемого алгоритма
  • options — различные опции, используемые при генерации хэша

Заключение

Новый API хэширования паролей, безусловно, удобнее, чем возня с crypt(). Если ваш сайт в настоящее время работает на PHP 5.5, то я настоятельно рекомендуется использовать новое API хэширования. Те, кто используют PHP 5.3.7 (или более новой версии), могут использовать библиотеку под названием password_compat которая эмулирует это API и автоматически отключает себя при использовании PHP версии 5.5+.

Источник

Оцените статью