PHP 8.3.4 Released!

password_hash

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_hashErstellt einen Passwort-Hash

Beschreibung

password_hash(string $password, string|int|null $algo, array $options = []): string

password_hash() erstellt einen neuen Passwort-Hash und benutzt dabei einen starken Einweg-Hashing-Algorithmus.

Die folgenden Algorithmen werden zur Zeit unterstützt:

  • PASSWORD_DEFAULT - Verwendet den bcrypt-Algorithmus (Standard in PHP 5.5.0). Es ist zu beachten, dass sich diese Konstante mit der Zeit ändern wird, wenn stärkere Algorithmen in PHP implementiert werden. Aus diesem Grund kann sich die Länge des zurückgegebenen Strings mit der Zeit ändern. Es wird deshalb empfohlen das Ergebnis in einem Datenbankfeld zu speichern, das mehr als 60 Zeichen speichern kann. (z. B. 255 Zeichen).
  • PASSWORD_BCRYPT - Verwendet den CRYPT_BLOWFISH-Algorithmus zum Erstellen des Hashes. Dieser erstellt einen crypt()-kompatiblen Hash und benutzt die "$2y$"-Kennung. Es wird immer ein 60 Zeichen langer String zurückgegeben, Bei einem Fehler wird false zurückgegeben.
  • PASSWORD_ARGON2I - Verwendet den Argon2i-Algorithmus zur Erstellung des Hashes. Dieser Algorithmus ist nur verfügbar, wenn PHP mit Argon2-Unterstützung kompiliert wurde.
  • PASSWORD_ARGON2ID - Verwendet den Argon2id-Algorithmus zur Erstellung des Hashes. Dieser Algorithmus ist nur verfügbar, wenn PHP mit Argon2-Unterstützung kompiliert wurde.

Unterstützte Optionen für PASSWORD_BCRYPT:

  • salt (string) - um manuell ein Salt anzugeben, das beim Hashing des Passworts verwendet wird. Es ist zu beachten, dass diese Option die automatische Generierung des Salt verhindert.

    Wenn diese Option nicht angegeben wird, erzeugt die Funktion password_hash() für jedes gehashte Passwort ein zufälliges Salt. Dies ist die vorgesehene Funktionsweise.

    Warnung

    Die salt-Option wird missbilligt. Es wird nun empfohlen, einfach das Salt zu verwenden, das standardmäßig erzeugt wird. Ab PHP 8.0.0 wird ein explizit angegebenes Salt ignoriert.

  • cost (int) - bezeichnet die algorithmischen Kosten, die verwendet werden sollen. Beispiele für diesen Wert finden Sie finden Sie auf der Seite crypt().

    Wenn diese Option nicht angegeben wird, wird ein Standardwert von 10 verwendet. Dies ist eine gute Basis für die Kosten, aber je nach Hardware sollten Sie in Betracht ziehen, den Wert zu erhöhen.

Unterstützte Optionen für PASSWORD_ARGON2I und PASSWORD_ARGON2ID:

  • memory_cost (int) - Maximaler Speicher (in Kibibytes), der zum Berechnen des Argon2-Hashes verwendet werden darf. Der Standardwert ist PASSWORD_ARGON2_DEFAULT_MEMORY_COST.

  • time_cost (int) - Maximale Zeit, die die das Berechnen des Argon2-Hashes dauern darf. Der Standardwert ist PASSWORD_ARGON2_DEFAULT_TIME_COST.

  • threads (int) - Anzahl der zu verwendenden Threads zum Berechnen des Argon2-Hashes. Der Standardwert ist PASSWORD_ARGON2_DEFAULT_THREADS.

    Warnung

    Nur verfügbar, wenn PHP libargon2 verwendet, nicht für libsodium-Implementierungen.

Parameter-Liste

password

Das Passwort des Benutzers.

Achtung

Die Verwendung von PASSWORD_BCRYPT als Algorithmus führt dazu, dass der Parameter password auf eine Höchstlänge von 72 Bytes gekürzt wird.

algo

Eine Konstante für den Passwort-Algorithmus, die den Algorithmus zum hashen des Passwortes angibt.

options

Ein assoziatives Array mit Optionen. Siehe auch Konstanten für Passwort-Algorithmen für Informationen zu den von den jeweiligen Algorithmen unterstützten Optionen.

Wenn diese Option weggelassen wird, wird ein zufälliges Salz erzeugt und die Standardkosten werden verwendet.

Rückgabewerte

Gibt den Passwort-Hash zurück.

Der verwendete Algorithmus, der Aufwand und das Salt werden als Teil des Hashes zurückgegeben. Daher sind alle Informationen, die benötigt werden, um den Hash zu verifizieren, darin enthalten. Dies erlaubt es der Funktion password_verify() den Hash zu überprüfen, ohne dass eine separate Speicherung für das Salt oder die Algorithmus-Informationen erforderlich ist.

Changelog

Version Beschreibung
8.0.0 password_hash() gibt im Fehlerfall nicht mehr false zurück; stattdessens wird ein ValueError ausgelöst, wenn der Passwort-Hashing-Algorithmus ungültig ist, oder ein Error, wenn das Passwort-Hashing aufgrund eines unbekannten Fehlers fehlschlug.
8.0.0 Der Parameter algo ist jetzt nullable (akzeptiert den NULL-Wert).
7.4.0 Der Parameter algo erwartet nun einen String, akzeptiert aber aus Gründen der Abwärtskompatibilität noch immer Integer.
7.4.0 Die Sodium-Erweiterung bietet eine alternative Implementierung für Argon2-Passwörter.
7.3.0 Mit PASSWORD_ARGON2ID wurde die Unterstützung für Argon2id-Passwörter hinzugefügt.
7.2.0 Mit PASSWORD_ARGON2I wurde die Unterstützung für Argon2i-Passwörter hinzugefügt.

Beispiele

Beispiel #1 password_hash()-Beispiel

<?php
/**
* Wir wollen nur unser Passwort mit dem aktuellen STANDARD-Algorithmus hashen.
* Dieser ist derzeit BCRYPT und liefert ein Ergebnis mit 60 Zeichen.
*
* Beachten Sie, dass sich STANDARD im Laufe der Zeit ändern kann, daher
* sollten Sie sich darauf vorbereiten, indem Sie die Speicherung von mehr als
* 60 Zeichen ermöglichen (255 wäre gut).
*/
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Beispiel #2 password_hash()-Beispiel mit manuell festgelegten Kosten

<?php
/**
* In diesem Fall wollen wir die Standardkosten für BCRYPT auf 12 erhöhen.
* Beachten Sie, dass wir auch auf BCRYPT umgestellt haben, das immer 60
* Zeichen haben wird.
*/
$optionen = [
'cost' => 12,
];
echo
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $optionen);
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Beispiel #3 password_hash()-Beispiel für die Suche nach angemessenen Kosten

<?php
/**
* Dieser Code führt einen Benchmark Ihres Servers durch, um festzustellen,
* wie hoch die Kosten sind, die Sie sich leisten können. Sie sollten die
* höchsten Kosten einstellen, die Sie sich leisten können, ohne dass der
* Server zu sehr verlangsamt wird. 10 ist ein guter Grundwert, und mehr ist
* gut, wenn Ihre Server schnell genug sind. Der folgende Code zielt auf eine
* Dehnungszeit von ≤ 350 Millisekunden ab, was eine geeignete Verzögerung für
* Systeme ist, die interaktive Anmeldungen verarbeiten.
*/
$zeitZiel = 0.350; // 350 Millisekunden

$kosten = 10;
do {
$kosten++;
$start = microtime(true);
password_hash("test", PASSWORD_BCRYPT, ["cost" => $kosten]);
$ende = microtime(true);
} while ((
$ende - $start) < $zeitZiel);

echo
"Ermittelte angemessene Kosten: " . $kosten;
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Ermittelte angemessene Kosten: 12

Beispiel #4 password_hash()-Beispiel, das Argon2i verwendet

<?php
echo 'Argon2i-Hash: ' . password_hash('rasmuslerdorf', PASSWORD_ARGON2I);
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Argon2i-Hash: $argon2i$v=19$m=1024,t=2,p=2$YzJBSzV4TUhkMzc3d3laeg$zqU/1IN0/AogfP4cmSJI1vc8lpXRW9/S0sYY2i2jHT0

Anmerkungen

Achtung

Es wird dringend empfohlen, dass Sie kein eigenes Salz für diese Funktion verwenden. Es wird automatisch ein sicheres Salt für Sie erzeugt, wenn Sie keines angeben.

Wie oben erwähnt, erzeugt die Angabe der Option salt in PHP 7.0 eine Missbilligungs-Warnung. Die Unterstützung für die manuelle Angabe eines Salzes wurde in PHP 8.0 entfernt.

Hinweis:

Es wird empfohlen, dass Sie diese Funktion auf Ihren Servern testen und den Kostenparameter so anpassen, dass die Ausführung der Funktion weniger als 350 Millisekunden auf interaktiven Systemen dauert. Das Skript im obigen Beispiel wird hilft Ihnen, einen guten Kostenwert für Ihre Hardware zu wählen.

Hinweis: Aktualisierungen der unterstützten Algorithmen durch diese Funktion (oder Änderungen am Standardalgorithmus) müssen den folgenden Regeln folgen:

  • Jeder neue Algorithmus muss für mindestens 1 Vollversion im Core von PHP sein, bevor er zum Standard wird. Wenn also z. B. ein neuer Algorithmus in 7.5.5 hinzugefügt wird, wäre er erst in 7.7 als Standard geeignet (da 7.6 die erste Vollversion wäre). Wenn aber ein anderer Algorithmus in 7.6.0 hinzugefügt würde, wäre auch dieser für die Standardeinstellung in 7.7.0 freigegeben.
  • Die Voreinstellung sollte sich nur bei einer Vollversion (7.3.0, 8.0.0, etc) ändern und nicht bei einer Korrekturversion. Die einzige Ausnahme hiervon ist in einem Notfall, wenn eine kritische Sicherheitslücke in der aktuellen Voreinstellung gefunden wurde.

Siehe auch

add a note

User Contributed Notes 10 notes

up
140
phpnetcomment201908 at lucb1e dot com
4 years ago
Since 2017, NIST recommends using a secret input when hashing memorized secrets such as passwords. By mixing in a secret input (commonly called a "pepper"), one prevents an attacker from brute-forcing the password hashes altogether, even if they have the hash and salt. For example, an SQL injection typically affects only the database, not files on disk, so a pepper stored in a config file would still be out of reach for the attacker. A pepper must be randomly generated once and can be the same for all users. Many password leaks could have been made completely useless if site owners had done this.

Since there is no pepper parameter for password_hash (even though Argon2 has a "secret" parameter, PHP does not allow to set it), the correct way to mix in a pepper is to use hash_hmac(). The "add note" rules of php.net say I can't link external sites, so I can't back any of this up with a link to NIST, Wikipedia, posts from the security stackexchange site that explain the reasoning, or anything... You'll have to verify this manually. The code:

// config.conf
pepper=c1isvFdxMDdmjOlvxpecFw

<?php
// register.php
$pepper = getConfigVariable("pepper");
$pwd = $_POST['password'];
$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);
$pwd_hashed = password_hash($pwd_peppered, PASSWORD_ARGON2ID);
add_user_to_database($username, $pwd_hashed);
?>

<?php
// login.php
$pepper = getConfigVariable("pepper");
$pwd = $_POST['password'];
$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);
$pwd_hashed = get_pwd_from_db($username);
if (
password_verify($pwd_peppered, $pwd_hashed)) {
echo
"Password matches.";
}
else {
echo
"Password incorrect.";
}
?>

Note that this code contains a timing attack that leaks whether the username exists. But my note was over the length limit so I had to cut this paragraph out.

Also note that the pepper is useless if leaked or if it can be cracked. Consider how it might be exposed, for example different methods of passing it to a docker container. Against cracking, use a long randomly generated value (like in the example above), and change the pepper when you do a new install with a clean user database. Changing the pepper for an existing database is the same as changing other hashing parameters: you can either wrap the old value in a new one and layer the hashing (more complex), you compute the new password hash whenever someone logs in (leaving old users at risk, so this might be okay depending on what the reason is that you're upgrading).

Why does this work? Because an attacker does the following after stealing the database:

password_verify("a", $stolen_hash)
password_verify("b", $stolen_hash)
...
password_verify("z", $stolen_hash)
password_verify("aa", $stolen_hash)
etc.

(More realistically, they use a cracking dictionary, but in principle, the way to crack a password hash is by guessing. That's why we use special algorithms: they are slower, so each verify() operation will be slower, so they can try much fewer passwords per hour of cracking.)

Now what if you used that pepper? Now they need to do this:

password_verify(hmac_sha256("a", $secret), $stolen_hash)

Without that $secret (the pepper), they can't do this computation. They would have to do:

password_verify(hmac_sha256("a", "a"), $stolen_hash)
password_verify(hmac_sha256("a", "b"), $stolen_hash)
...
etc., until they found the correct pepper.

If your pepper contains 128 bits of entropy, and so long as hmac-sha256 remains secure (even MD5 is technically secure for use in hmac: only its collision resistance is broken, but of course nobody would use MD5 because more and more flaws are found), this would take more energy than the sun outputs. In other words, it's currently impossible to crack a pepper that strong, even given a known password and salt.
up
162
martinstoeckli
11 years ago
There is a compatibility pack available for PHP versions 5.3.7 and later, so you don't have to wait on version 5.5 for using this function. It comes in form of a single php file:
https://github.com/ircmaxell/password_compat
up
4
bhare at duck dot com
6 months ago
If you are you going to use bcrypt then you should pepper the passwords with random large string, as commodity hardware can break bcrypt 8 character passwords within an hour; https://www.tomshardware.com/news/eight-rtx-4090s-can-break-passwords-in-under-an-hour
up
42
nicoSWD
10 years ago
I agree with martinstoeckli,

don't create your own salts unless you really know what you're doing.

By default, it'll use /dev/urandom to create the salt, which is based on noise from device drivers.

And on Windows, it uses CryptGenRandom().

Both have been around for many years, and are considered secure for cryptography (the former probably more than the latter, though).

Don't try to outsmart these defaults by creating something less secure. Anything that is based on rand(), mt_rand(), uniqid(), or variations of these is *not* good.
up
25
Lyo Mi
8 years ago
Please note that password_hash will ***truncate*** the password at the first NULL-byte.

http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html

If you use anything as an input that can generate NULL bytes (sha1 with raw as true, or if NULL bytes can naturally end up in people's passwords), you may make your application much less secure than what you might be expecting.

The password
$a = "\01234567";
is zero bytes long (an empty password) for bcrypt.

The workaround, of course, is to make sure you don't ever pass NULL-bytes to password_hash.
up
19
martinstoeckli
11 years ago
In most cases it is best to omit the salt parameter. Without this parameter, the function will generate a cryptographically safe salt, from the random source of the operating system.
up
23
Cloxy
10 years ago
You can produce the same hash in php 5.3.7+ with crypt() function:

<?php

$salt
= mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt('rasmuslerdorf', '$2y$10$'.$salt.'$');

echo
$hash;

?>
up
9
Mike Robinson
9 years ago
For passwords, you generally want the hash calculation time to be between 250 and 500 ms (maybe more for administrator accounts). Since calculation time is dependent on the capabilities of the server, using the same cost parameter on two different servers may result in vastly different execution times. Here's a quick little function that will help you determine what cost parameter you should be using for your server to make sure you are within this range (note, I am providing a salt to eliminate any latency caused by creating a pseudorandom salt, but this should not be done when hashing passwords):

<?php
/**
* @Param int $min_ms Minimum amount of time in milliseconds that it should take
* to calculate the hashes
*/
function getOptimalBcryptCostParameter($min_ms = 250) {
for (
$i = 4; $i < 31; $i++) {
$options = [ 'cost' => $i, 'salt' => 'usesomesillystringforsalt' ];
$time_start = microtime(true);
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
$time_end = microtime(true);
if ((
$time_end - $time_start) * 1000 > $min_ms) {
return
$i;
}
}
}
echo
getOptimalBcryptCostParameter(); // prints 12 in my case
?>
up
2
ms1 at rdrecs dot com
4 years ago
Timing attacks simply put, are attacks that can calculate what characters of the password are due to speed of the execution.

More at...
https://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategy

I have added code to phpnetcomment201908 at lucb1e dot com's suggestion to make this possible "timing attack" more difficult using the code phpnetcomment201908 at lucb1e dot com posted.

$pph_strt = microtime(true);

//...
/*The code he posted for login.php*/
//...

$end = (microtime(true) - $pph_strt);

$wait = bcmul((1 - $end), 1000000); // usleep(250000) 1/4 of a second

usleep ( $wait );

echo "<br>Execution time:".(microtime(true) - $pph_strt)."; ";

Note I suggest changing the wait time to suit your needs but make sure that it is more than than the highest execution time the script takes on your server.

Also, this is my workaround to obfuscate the execution time to nullify timing attacks. You can find an in-depth discussion and more from people far more equipped than I for cryptography at the link I posted. I do not believe this was there but there are others. It is where I found out what timing attacks were as I am new to this but would like solid security.
up
-8
Anonymous
4 years ago
According to the draft specification, Argon2di is the recommended mode of operation:

> 9.4. Recommendations
>
> The Argon2id variant with t=1 and maximum available memory is
> recommended as a default setting for all environments. This setting
> is secure against side-channel attacks and maximizes adversarial
> costs on dedicated bruteforce hardware.

source: https://tools.ietf.org/html/draft-irtf-cfrg-argon2-06#section-9.4
To Top