php写一个md5/sha1+salt密码类

最近暴露出的明文密码事件,自己以前一直是使用md5直接保存,了解一下暴力破解md5也是很容易攻破,google了一下大家推荐md5/sha1+salt的方式,在保证性能的情况下,安全性也提高了。今晚没事自己写了一个简单的处理类。

<?php
/**
* cypt & check password
* author: zweiwei
* email: lnnujxxy@gmail.com
* date: 2012/01/30
*/
class Security {
private static $defaultSalt = '}#f4ga~g%7hjg4&j(7mk?/!bj30ab-wi=6^7-$^R9F|GK5J#E6WT;IO[JN';

public static function cryptPassword($password, $uid=null) {
self::isVaildPassword($password);

$salt = self::generateSalt($uid);
return md5(sha1($salt.$password));

}

public static function checkPassword($cryptPassword, $password, $uid=null) {
if(strlen($cryptPassword) !== 32) {
throw new Exception("cryptPassword :".$cryptPassword." length is wrong!");
}
self::isVaildPassword($password);

$salt = self::generateSalt($uid);
if(md5(sha1($salt.$password)) === $cryptPassword) {
return true;
}
return false;
}

private static function generateSalt($uid=null) {
$md5Str = is_null($uid) ? md5($uid) : md5(self::$defaultSalt);
return substr($md5Str, 8, 16);
}

private static function isVaildPassword($password) {
if(!$password || strlen($password) < 8) {
throw new Exception("password :".$password." must be longer than 8");
}
// contain ~!@#$%^&*
if(!preg_match('/[~!@#$%^&]/', $password)) {
throw new Exception("password :".$password." must contain special characters(~!@#$%^&)");
}
}
}

测试代码:

require_once 'PHPUnit/Autoload.php';

class SecurityTest extends PHPUnit_Framework_TestCase {
public function testCryptPassword()
{
$cryptPassword = Security::cryptPassword('12345686000&$~', 123);
$this->assertEquals(32, strlen($cryptPassword));

$cryptPassword = Security::cryptPassword('12345686000&$~');
$this->assertEquals(32, strlen($cryptPassword));
}

public function testCheckPassword()
{
$this->assertTrue(Security::checkPassword(Security::cryptPassword('12345686000&$~', 123), '12345686000&$~', 123));

$this->assertFalse(Security::checkPassword(Security::cryptPassword('12345686000&$~', 123), '12345686000&$', 123));
}
}


参考:
http://jinchishuxue.iteye.com/blog/1126271
http://woshixushigang.iteye.com/blog/1181423
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值