1. scrypt
암호화 백업 서비스 tarsnap을 운영하는
캐나다 프로그래머 콜린 퍼시벌이 개발한 암호화 알고리듬입니다.
뚫기 어려운 걸로 말하자면 비교 대상이 없는 막강한 알고리듬이지만,
너무 최신이라 PHP에서는 전혀 사용할 수 없으므로 패스.
2. bcrypt
해외에서 비밀번호 암호화에 대해 물어보면 즉시 돌아오는 모범답안입니다.
예전부터 널리 사용되어 온 blowfish 양방향 암호화 알고리듬을 단방향으로 개조한 것으로,
위에 언급한 scrypt를 제외하면 가장 막강한 후보입니다.
PHP 5.5 이상에서는 아예 bcrypt 암호화 함수를 내장하고 있으므로
아래와 같이 간단하게 사용 가능합니다.
암호화: $hash = password_hash($password, PASSWORD_DEFAULT);
여기서 반환하는 $hash 값을 DB에 저장해 두었다가 아래에서 확인하는 데 씁니다.
확인: if (password_verify($password, $hash)) {
// 비밀번호가 맞음
} else {
// 비밀번호가 틀림
}
include 파일
<?php
/**
* A Compatibility library with PHP 5.5's simplified password hashing API.
*
* @author Anthony Ferrara <ircmaxell@php.net>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2012 The Authors
*/
/*
http://kiwinote.tistory.com/40
*/
namespace {
if (!defined('PASSWORD_BCRYPT')) {
/**
* PHPUnit Process isolation caches constants, but not function declarations.
* So we need to check if the constants are defined separately from
* the functions to enable supporting process isolation in userland
* code.
*/
define('PASSWORD_BCRYPT', 1);
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
define('PASSWORD_BCRYPT_DEFAULT_COST', 10);
}
if (!function_exists('password_hash')) {
/**
* Hash the password using the specified algorithm
*
* @param string $password The password to hash
* @param int $algo The algorithm to use (Defined by PASSWORD_* constants)
* @param array $options The options for the algorithm to use
*
* @return string|false The hashed password, or false on error.
*/
function password_hash($password, $algo, array $options = array()) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
return null;
}
if (is_null($password) || is_int($password)) {
$password = (string) $password;
}
if (!is_string($password)) {
trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
return null;
}
if (!is_int($algo)) {
trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING);
return null;
}
$resultLength = 0;
switch ($algo) {
case PASSWORD_BCRYPT:
$cost = PASSWORD_BCRYPT_DEFAULT_COST;
if (isset($options['cost'])) {
$cost = (int) $options['cost'];
if ($cost < 4 || $cost > 31) {
trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
return null;
}
}
// The length of salt to generate
$raw_salt_len = 16;
// The length required in the final serialization
$required_salt_len = 22;
$hash_format = sprintf("$2y$%02d$", $cost);
// The expected length of the final crypt() output
$resultLength = 60;
break;
default:
trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
return null;
}
$salt_req_encoding = false;
if (isset($options['salt'])) {
switch (gettype($options['salt'])) {
case 'NULL':
case 'boolean':
case 'integer':
case 'double':
case 'string':
$salt = (string) $options['salt'];
break;
case 'object':
if (method_exists($options['salt'], '__tostring')) {
$salt = (string) $options['salt'];
break;
}
case 'array':
case 'resource':
default:
trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
return null;
}
if (PasswordCompat\binary\_strlen($salt) < $required_salt_len) {
trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", PasswordCompat\binary\_strlen($salt), $required_salt_len), E_USER_WARNING);
return null;
} elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
$salt_req_encoding = true;
}
} else {
$buffer = '';
$buffer_valid = false;
if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
$buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
$strong = false;
$buffer = openssl_random_pseudo_bytes($raw_salt_len, $strong);
if ($buffer && $strong) {
$buffer_valid = true;
}
}
if (!$buffer_valid && @is_readable('/dev/urandom')) {
$file = fopen('/dev/urandom', 'r');
$read = 0;
$local_buffer = '';
while ($read < $raw_salt_len) {
$local_buffer .= fread($file, $raw_salt_len - $read);
$read = PasswordCompat\binary\_strlen($local_buffer);
}
fclose($file);
if ($read >= $raw_salt_len) {
$buffer_valid = true;
}
$buffer = str_pad($buffer, $raw_salt_len, "\0") ^ str_pad($local_buffer, $raw_salt_len, "\0");
}
if (!$buffer_valid || PasswordCompat\binary\_strlen($buffer) < $raw_salt_len) {
$buffer_length = PasswordCompat\binary\_strlen($buffer);
for ($i = 0; $i < $raw_salt_len; $i++) {
if ($i < $buffer_length) {
$buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
} else {
$buffer .= chr(mt_rand(0, 255));
}
}
}
$salt = $buffer;
$salt_req_encoding = true;
}
if ($salt_req_encoding) {
// encode string with the Base64 variant used by crypt
$base64_digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
$bcrypt64_digits =
'./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$base64_string = base64_encode($salt);
$salt = strtr(rtrim($base64_string, '='), $base64_digits, $bcrypt64_digits);
}
$salt = PasswordCompat\binary\_substr($salt, 0, $required_salt_len);
$hash = $hash_format . $salt;
$ret = crypt($password, $hash);
if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != $resultLength) {
return false;
}
return $ret;
}
/**
* Get information about the password hash. Returns an array of the information
* that was used to generate the password hash.
*
* array(
* 'algo' => 1,
* 'algoName' => 'bcrypt',
* 'options' => array(
* 'cost' => PASSWORD_BCRYPT_DEFAULT_COST,
* ),
* )
*
* @param string $hash The password hash to extract info from
*
* @return array The array of information about the hash.
*/
function password_get_info($hash) {
$return = array(
'algo' => 0,
'algoName' => 'unknown',
'options' => array(),
);
if (PasswordCompat\binary\_substr($hash, 0, 4) == '$2y$' && PasswordCompat\binary\_strlen($hash) == 60) {
$return['algo'] = PASSWORD_BCRYPT;
$return['algoName'] = 'bcrypt';
list($cost) = sscanf($hash, "$2y$%d$");
$return['options']['cost'] = $cost;
}
return $return;
}
/**
* Determine if the password hash needs to be rehashed according to the options provided
*
* If the answer is true, after validating the password using password_verify, rehash it.
*
* @param string $hash The hash to test
* @param int $algo The algorithm used for new password hashes
* @param array $options The options array passed to password_hash
*
* @return boolean True if the password needs to be rehashed.
*/
function password_needs_rehash($hash, $algo, array $options = array()) {
$info = password_get_info($hash);
if ($info['algo'] !== (int) $algo) {
return true;
}
switch ($algo) {
case PASSWORD_BCRYPT:
$cost = isset($options['cost']) ? (int) $options['cost'] : PASSWORD_BCRYPT_DEFAULT_COST;
if ($cost !== $info['options']['cost']) {
return true;
}
break;
}
return false;
}
/**
* Verify a password against a hash using a timing attack resistant approach
*
* @param string $password The password to verify
* @param string $hash The hash to verify against
*
* @return boolean If the password matches the hash
*/
function password_verify($password, $hash) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
return false;
}
$ret = crypt($password, $hash);
if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != PasswordCompat\binary\_strlen($hash) || PasswordCompat\binary\_strlen($ret) <= 13) {
return false;
}
$status = 0;
for ($i = 0; $i < PasswordCompat\binary\_strlen($ret); $i++) {
$status |= (ord($ret[$i]) ^ ord($hash[$i]));
}
return $status === 0;
}
}
}
namespace PasswordCompat\binary {
if (!function_exists('PasswordCompat\\binary\\_strlen')) {
/**
* Count the number of bytes in a string
*
* We cannot simply use strlen() for this, because it might be overwritten by the mbstring extension.
* In this case, strlen() will count the number of *characters* based on the internal encoding. A
* sequence of bytes might be regarded as a single multibyte character.
*
* @param string $binary_string The input string
*
* @internal
* @return int The number of bytes
*/
function _strlen($binary_string) {
if (function_exists('mb_strlen')) {
return mb_strlen($binary_string, '8bit');
}
return strlen($binary_string);
}
/**
* Get a substring based on byte limits
*
* @see _strlen()
*
* @param string $binary_string The input string
* @param int $start
* @param int $length
*
* @internal
* @return string The substring
*/
function _substr($binary_string, $start, $length) {
if (function_exists('mb_substr')) {
return mb_substr($binary_string, $start, $length, '8bit');
}
return substr($binary_string, $start, $length);
}
/**
* Check if current PHP version is compatible with the library
*
* @return boolean the check result
*/
function check() {
static $pass = NULL;
if (is_null($pass)) {
if (function_exists('crypt')) {
$hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
$test = crypt("password", $hash);
$pass = $test == $hash;
} else {
$pass = false;
}
}
return $pass;
}
}
}
?>
3. PBKDF2
HP 4.4 ~ 5.0 환경에서는 솔트를 생성하여 SHA1 함수를 수천 번 적용하는 방식을 사용하고,
PHP 5.1 이상에서는 공식 라이브러리와 동일하게 SHA256 해시를 적용합니다.
공식 라이브러리는 mcrypt 모듈이 필요하지만, 이건 그것도 필요없습니다. 그냥 PHP만 있으면 됩니다.
그냥 SHA1 함수만 쓰는 것이 아니라 PBKDF2 스펙에서 요구하는 HMAC 알고리듬을 구현하였으므로
생성된 해시는 공식 라이브러리와 100% 호환됩니다.
즉, 나중에 PHP 버전을 업그레이드하실 경우 공식 라이브러리로 바꿔도 무방합니다.
사용 방법도 공식 라이브러리와 100% 동일합니다.
암호화할 때: $hash = create_hash($password);
여기서 반환하는 $hash 값을 DB에 저장해 두었다가 아래에서 확인하는 데 씁니다.
확인할 때: if (validate_password($password, $hash)) {
// 비밀번호가 맞음
} else {
// 비밀번호가 틀림
}
참고: 같은 비번이라도 해시할 때마다 결과가 다르게 나오는 것은 정상입니다. (솔트를 사용하기 때문)
같은 비번으로 생성한 모든 해시는 validate_password() 함수를 통과할 수 있습니다.
따라서 기존의 md5 방식대로 한 번 더 해시해서 결과를 비교하는 것이 아니라
비번 확인시에는 반드시 validate_password() 함수를 사용해야 합니다.
include 파일
<?php
/*
* Password Hashing with PBKDF2 (http://crackstation.net/hashing-security.htm).
* Copyright (c) 2013, Taylor Hornby
* All rights reserved.
*
* Modified to Work with Older Versions of PHP
* Copyright (c) 2014, Kijin Sung
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// These constants may be changed without breaking existing hashes.
define('PBKDF2_COMPAT_HASH_ALGORITHM', 'SHA256');
define('PBKDF2_COMPAT_ITERATIONS', 12000);
define('PBKDF2_COMPAT_SALT_BYTES', 24);
define('PBKDF2_COMPAT_HASH_BYTES', 24);
// Calculates a hash from the given password.
function create_hash($password, $force_compat = false)
{
// Generate the salt.
if (function_exists('mcrypt_create_iv')) {
$salt = base64_encode(mcrypt_create_iv(PBKDF2_COMPAT_SALT_BYTES, MCRYPT_DEV_URANDOM));
} elseif (file_exists('/dev/urandom') && $fp = @fopen('/dev/urandom', 'r')) {
$salt = base64_encode(fread($fp, PBKDF2_COMPAT_SALT_BYTES));
} else {
$salt = '';
for ($i = 0; $i < PBKDF2_COMPAT_SALT_BYTES; $i += 2) {
$salt .= pack('S', mt_rand(0, 65535));
}
$salt = base64_encode(substr($salt, 0, PBKDF2_COMPAT_SALT_BYTES));
}
// Determine the best supported algorithm and iteration count.
$algo = strtolower(PBKDF2_COMPAT_HASH_ALGORITHM);
$iterations = PBKDF2_COMPAT_ITERATIONS;
if ($force_compat || !function_exists('hash_algos') || !in_array($algo, hash_algos())) {
$algo = false; // This flag will be detected by pbkdf2_default()
$iterations = round($iterations / 5); // PHP 4 is very slow. Don't cause too much server load.
}
// Return format: algorithm:iterations:salt:hash
$pbkdf2 = pbkdf2_default($algo, $password, $salt, $iterations, PBKDF2_COMPAT_HASH_BYTES);
$prefix = $algo ? $algo : 'sha1';
return $prefix . ':' . $iterations . ':' . $salt . ':' . base64_encode($pbkdf2);
}
// Checks whether a password matches a previously calculated hash
function validate_password($password, $hash)
{
// Split the hash into 4 parts.
$params = explode(':', $hash);
if (count($params) < 4) return false;
// Recalculate the hash and compare it with the original.
$pbkdf2 = base64_decode($params[3]);
$pbkdf2_check = pbkdf2_default($params[0], $password, $params[2], (int)$params[1], strlen($pbkdf2));
return slow_equals($pbkdf2, $pbkdf2_check);
}
// Checks whether a hash needs upgrading.
function needs_upgrade($hash)
{
// Get the current algorithm and iteration count.
$params = explode(':', $hash);
if (count($params) < 4) return true;
$algo = $params[0];
$iterations = (int)$params[1];
// Compare the current hash with the best supported options.
if (!function_exists('hash_algos') || !in_array($algo, hash_algos())) {
return false;
} elseif ($algo === strtolower(PBKDF2_COMPAT_HASH_ALGORITHM) && $iterations >= PBKDF2_COMPAT_ITERATIONS) {
return false;
} else {
return true;
}
}
// Compares two strings $a and $b in length-constant time.
function slow_equals($a, $b)
{
$diff = strlen($a) ^ strlen($b);
for($i = 0; $i < strlen($a) && $i < strlen($b); $i++) {
$diff |= ord($a[$i]) ^ ord($b[$i]);
}
return $diff === 0;
}
// PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
// Test vectors can be found here: https://www.ietf.org/rfc/rfc6070.txt
// This implementation of PBKDF2 was originally created by https://defuse.ca
// With improvements by http://www.variations-of-shadow.com
function pbkdf2_default($algo, $password, $salt, $count, $key_length)
{
// Sanity check.
if ($count <= 0 || $key_length <= 0) {
trigger_error('PBKDF2 ERROR: Invalid parameters.', E_USER_ERROR);
}
// Check if we should use the fallback function.
if (!$algo) return pbkdf2_fallback($password, $salt, $count, $key_length);
// Check if the selected algorithm is available.
$algo = strtolower($algo);
if (!function_exists('hash_algos') || !in_array($algo, hash_algos())) {
if ($algo === 'sha1') {
return pbkdf2_fallback($password, $salt, $count, $key_length);
} else {
trigger_error('PBKDF2 ERROR: Hash algorithm not supported.', E_USER_ERROR);
}
}
// Use built-in function if available.
if (function_exists('hash_pbkdf2')) {
return hash_pbkdf2($algo, $password, $salt, $count, $key_length, true);
}
// Count the blocks.
$hash_length = strlen(hash($algo, '', true));
$block_count = ceil($key_length / $hash_length);
// Hash it!
$output = '';
for ($i = 1; $i <= $block_count; $i++) {
$last = $salt . pack('N', $i); // $i encoded as 4 bytes, big endian.
$last = $xorsum = hash_hmac($algo, $last, $password, true); // first iteration.
for ($j = 1; $j < $count; $j++) { // The other $count - 1 iterations.
$xorsum ^= ($last = hash_hmac($algo, $last, $password, true));
}
$output .= $xorsum;
}
// Truncate and return.
return substr($output, 0, $key_length);
}
// Fallback function using sha1() and a pure-PHP implementation of HMAC.
// The result is identical to the default function when used with SHA-1.
// But it is approximately 1.6x slower than the hash_hmac() function of PHP 5.1.2+,
// And approximately 2.3x slower than the hash_pbkdf2() function of PHP 5.5+.
function pbkdf2_fallback($password, $salt, $count, $key_length)
{
// Count the blocks.
$hash_length = 20;
$block_count = ceil($key_length / $hash_length);
// Prepare the HMAC key and padding.
if (strlen($password) > 64) {
$password = str_pad(sha1($password, true), 64, chr(0));
} else {
$password = str_pad($password, 64, chr(0));
}
$opad = str_repeat(chr(0x5C), 64) ^ $password;
$ipad = str_repeat(chr(0x36), 64) ^ $password;
// Hash it!
$output = '';
for ($i = 1; $i <= $block_count; $i++) {
$last = $salt . pack('N', $i);
$xorsum = $last = pack('H*', sha1($opad . pack('H*', sha1($ipad . $last))));
for ($j = 1; $j < $count; $j++) {
$last = pack('H*', sha1($opad . pack('H*', sha1($ipad . $last))));
$xorsum ^= $last;
}
$output .= $xorsum;
}
// Truncate and return.
return substr($output, 0, $key_length);
}
[PHP] isset() empty() 차이 (0) | 2021.09.17 |
---|---|
[PHP] $_SERVER['DOCUMENT_ROOT'] (0) | 2021.09.15 |
암호화 단방향 복호화 해싱 (0) | 2021.09.10 |
PHP Warning: date(): It is not safe to rely on the system's timezone settings 타임존 에러 (0) | 2021.09.09 |
[PHP] 5.2 버전 이하 암호하 (0) | 2021.09.08 |
댓글 영역