Laravel 비밀번호 해싱(솔트 포함)
Recently we went deep into the Laravel authentication system for some improvements and to add Multi-Factor authentication. I discovered some interesting details on how Laravel password hashing works.
This article can help you understand how secure your application is from this point of view or if it is necessary to make some changes in your PHP app to increase security.
Spoiler: Despite the title of the article, Laravel doesn't use a salt to hash your user's password, PHP does.
You can follow me on Linkedin or X. I post about building my SaaS product.
Hashing is different from Encryption
To avoid any misunderstanding, let me clarify that Hashing and Encryption are two very different things. Hashing is one way. Starting from a hash you cannot get back to the original string. Encryption instead is two ways. You can encrypt and decrypt strings.In fact these two features are provided through two different Laravel Facades: Illuminate\Support\Facades\Hash (for hashing), Illuminate\Support\Facades\Crypt (for encryption).
In the case of passwords, we want to store the hash so even in case of a data breach there is no way to get back the original password so the user credentials still protected.
How does Laravel make the password hash?
Obviously with the make method on the Hash service:
\Illuminate\Support\Facades\Hash::make(‘password’); // Output $2y$10$PeZ29z5axgJUZiy01tMBMuQuego6WLCDUV34LJbVowg4AKcZFl4mC
If you run this instruction multiple times you will get a different result each time:
$2y$10$PeZ29z5axgJUZiy01tMBMuQuego6WLCDUV34LJbVowg4AKcZFl4mC $2y$10$cYoHztp3QwzRvdTmzEE5xeXfXjbc6Ix3C9LhBungA/DIHcBLtgAE2 $2y$10$Mz30EAiaHtZZ1J5m6yrVbuHJcZr4r4iV.RYGX8I.pZ9tT2wThGPKW
So, How the hell does Laravel compare two passwords to check if they are the same? It's the check we need to do when a user is logging in.
The counter part of the make() method is check():
use Illuminate\Support\Facades\Hash; // Stored hashed password retrieved from the database $storedHash = '$2y$10$Oi4mNb5kKDWtVzbs6fLCie.Uy1eG1n0BnDO1QazrF8b1/LJZVWJSO'; // User-provided password during login attempt $userInputPassword = 'password'; // Verify if the user-provided password matches the stored hash if (Hash::check($userInputPassword, $storedHash)) { echo "Password verified!"; } else { echo "Invalid password!"; }
Laravel Password Hashing is a wrapper of PHP password functions
The Laravel password hashing component is an abstraction to use two native PHP functions with a predefined setup: password_hash, and password_verify. Both are a native wrappers of the low level crypt function.
This are the internal implementation of the two methods in the Laravel BcryptHasher:
Hash::make($password); public function make($value, array $options = []) { $hash = password_hash($value, PASSWORD_BCRYPT, [ 'cost' => $this->cost($options), ]); if ($hash === false) { throw new RuntimeException('Bcrypt hashing not supported.'); } return $hash; }
Hash::check($password, $storedHash); public function check($value, $hashedValue, array $options = []) { if (is_null($hashedValue) || strlen($hashedValue) === 0) { return false; } return password_verify($value, $hashedValue); }
As mentioned in the PHP documentation:
password_hash() uses a strong hash, generates a strong salt, and applies proper rounds automatically. password_hash() is a simple crypt() wrapper and compatible with existing password hashes. Use of password_hash() is encouraged.
In the examples above I reported some results of the Hash::make() that are the result of the password_hash() function eventually. You can notice the same pattern at the beginning of the string. It's a composition of the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the password_verify() function to verify the hash without needing separate storage for the salt or algorithm information.
Internally, the password_verify() function works by performing the following steps:
Extracting Parameters: It extracts the parameters stored within the hash string itself. These parameters include the hashing algorithm, the cost, and the salt.
Hashing the Input Password: Using the extracted parameters, password_verify() rehashes the user-provided password using the same algorithm, salt, and cost factor that were used to generate the stored hash.
Comparison: After rehashing the input password, it compares the resulting hash with the stored hash. If the two hashes match, the input password is correct.
Here is an example of how the password_verify() function can be implemented in plain PHP so you can understand the process:
function password_verify($userInputPassword, $storedHash) { // Extract parameters from the stored hash $params = explode('$', $storedHash); $algorithm = $params[1]; $cost = (int)$params[2]; $salt = $params[3]; // Rehash the user input password using the extracted parameters $rehashedPassword = crypt($userInputPassword, '$' . $algorithm . '$' . $cost . '$' . $salt); // Compare the rehashed password with the stored hash if ($rehashedPassword === $storedHash) { return true; } else { return false; } }
Security considerations
password_hash() already generates a strong hash with a salt. From the Laravel configuration you can eventually change the cost factor through the bcrypt.rounds parameter in the config/hashing.php file.
/* |-------------------------------------------------------------------------- | Bcrypt Options |-------------------------------------------------------------------------- | | Here you may specify the configuration options that should be used when | passwords are hashed using the Bcrypt algorithm. This will allow you | to control the amount of time it takes to hash the given password. | */ 'bcrypt' => [ 'rounds' => env('BCRYPT_ROUNDS', 10), ],
Increasing the cost factor (number of rounds) in the Bcrypt algorithm generally improves the security of passwords by making password hashing more computationally intensive and resistant to brute-force attacks.
For example the default value of the rounds parameter is 10, I use 12 in my application to strengthen my passwords a bit.
Monitor your PHP application for free
Inspector is a Code Execution Monitoring tool specifically designed for software developers. You don't need to install anything at the server level, just install the composer package and you are ready to go.
Inspector is super easy and PHP friendly. You can try our Laravel or Symfony package.
HTTP 모니터링, 데이터베이스 쿼리 통찰력, 경고 및 알림을 선호하는 메시징 환경으로 전달하는 기능을 찾고 있다면 Inspector를 무료로 사용해 보세요. 계정을 등록하세요.
또는 웹사이트에서 자세한 내용을 알아보세요: https://inspector.dev
위 내용은 Laravel 비밀번호 해싱(솔트 포함)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP에서 Password_hash 및 Password_Verify 기능을 사용하여 보안 비밀번호 해싱을 구현해야하며 MD5 또는 SHA1을 사용해서는 안됩니다. 1) Password_hash는 보안을 향상시키기 위해 소금 값이 포함 된 해시를 생성합니다. 2) Password_verify 암호를 확인하고 해시 값을 비교하여 보안을 보장합니다. 3) MD5 및 SHA1은 취약하고 소금 값이 부족하며 현대 암호 보안에는 적합하지 않습니다.

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP 유형은 코드 품질과 가독성을 향상시키기위한 프롬프트입니다. 1) 스칼라 유형 팁 : PHP7.0이므로 int, float 등과 같은 기능 매개 변수에 기본 데이터 유형을 지정할 수 있습니다. 2) 반환 유형 프롬프트 : 기능 반환 값 유형의 일관성을 확인하십시오. 3) Union 유형 프롬프트 : PHP8.0이므로 기능 매개 변수 또는 반환 값에 여러 유형을 지정할 수 있습니다. 4) Nullable 유형 프롬프트 : NULL 값을 포함하고 널 값을 반환 할 수있는 기능을 포함 할 수 있습니다.

PHP는 여전히 역동적이며 현대 프로그래밍 분야에서 여전히 중요한 위치를 차지하고 있습니다. 1) PHP의 단순성과 강력한 커뮤니티 지원으로 인해 웹 개발에 널리 사용됩니다. 2) 유연성과 안정성은 웹 양식, 데이터베이스 작업 및 파일 처리를 처리하는 데 탁월합니다. 3) PHP는 지속적으로 발전하고 최적화하며 초보자 및 숙련 된 개발자에게 적합합니다.

PHP와 Python은 고유 한 장점과 단점이 있으며 선택은 프로젝트 요구와 개인 선호도에 달려 있습니다. 1.PHP는 대규모 웹 애플리케이션의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 데이터 과학 및 기계 학습 분야를 지배합니다.

PHP는 특히 빠른 개발 및 동적 컨텐츠를 처리하는 데 웹 개발에 적합하지만 데이터 과학 및 엔터프라이즈 수준의 애플리케이션에는 적합하지 않습니다. Python과 비교할 때 PHP는 웹 개발에 더 많은 장점이 있지만 데이터 과학 분야에서는 Python만큼 좋지 않습니다. Java와 비교할 때 PHP는 엔터프라이즈 레벨 애플리케이션에서 더 나빠지지만 웹 개발에서는 더 유연합니다. JavaScript와 비교할 때 PHP는 백엔드 개발에서 더 간결하지만 프론트 엔드 개발에서는 JavaScript만큼 좋지 않습니다.
