CakePHPのハッシュ化後のパスワードを取得するためのメモ
はじめに
CakePHP2から別のフレームワークへ移行したい場合にログインパスワードを変換したい時など、CakePHPで構築したシステムと同様のハッシュ化後のログインパスワードを必要とする際のメモ
使い方
以下のコードを実行すると、ハッシュ化後のhogehogeの結果が出力されます。
$cake_hashed_password = new cake_hashed_password; $password = 'hogehoge'; $cake_hashed_password->salt = 'abcdefghijklmnopqrstuvwxyz'; echo $cake_hashed_password->hash($password, null, true);
コード
CakePHP2の/lib/Cake/Controller/Component/AuthComponent.phpを参考に作成 (というか、ほとんどそのまま)
<?php class cake_hashed_password { var $salt = null; public function hash($string, $type = null, $salt = false) { if (empty($type)) { $type = null; } $type = strtolower($type); if ($type === 'blowfish') { return $this->_crypt($string, $salt); } if ($salt) { if (!is_string($salt)) { $salt = $cake_hashed_password->salt; } $string = $salt . $string; } if (!$type || $type == 'sha1') { if (function_exists('sha1')) { return sha1($string); } $type = 'sha256'; } if ($type == 'sha256' && function_exists('mhash')) { return bin2hex(mhash(MHASH_SHA256, $string)); } if (function_exists('hash')) { return hash($type, $string); } return md5($string); } private function _salt($length = 22) { $salt = str_replace( array('+', '='), '.', base64_encode(sha1(uniqid($cake_hashed_password->salt, true), true)) ); return substr($salt, 0, $length); } private function _crypt($password, $salt = false) { if ($salt === false) { $salt = $this->_salt(22); $salt = vsprintf('$2a$%02d$%s', array(self::$hashCost, $salt)); } if ($salt === true || strpos($salt, '$2a$') !== 0 || strlen($salt) < 29) { return ''; } return crypt($password, $salt); } }