Created
August 14, 2012 04:47
-
-
Save leizongmin/3346320 to your computer and use it in GitHub Desktop.
Node.js/PHP 密码验证相关函数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var crypto = require('crypto'); | |
/** | |
* 32位MD5加密 | |
* | |
* @param {string} text 文本 | |
* @return {string} | |
*/ | |
var md5 = function (text) { | |
return crypto.createHash('md5').update(text).digest('hex'); | |
}; | |
/** | |
* 加密密码 | |
* | |
* @param {string} password | |
* @return {string} | |
*/ | |
var encryptPassword = function (password) { | |
var random = md5(Math.random() + '' + Math.random()).toUpperCase(); | |
var left = random.substr(0, 2); | |
var right = random.substr(-2); | |
var newpassword = md5(left + password + right).toUpperCase(); | |
return [left, newpassword, right].join(':'); | |
}; | |
/** | |
* 验证密码 | |
* | |
* @param {string} password 待验证的密码 | |
* @param {string} encrypted 密码加密字符串 | |
* @return {bool} | |
*/ | |
var validatePassword = function (password, encrypted) { | |
var random = encrypted.toUpperCase().split(':'); | |
if (random.length < 3) return false; | |
var left = random[0]; | |
var right = random[2]; | |
var main = random[1]; | |
var newpassword = md5(left + password + right).toUpperCase(); | |
return newpassword === main; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* PHP版本 | |
*/ | |
/** | |
* 加密密码 | |
* | |
* @param {string} $password | |
* @return {string} | |
*/ | |
function encryptPassword ($password) { | |
$random = strtoupper(md5(rand().rand())); | |
$left = substr($random, 0, 2); | |
$right = substr($random, -2); | |
$newpassword = strtoupper(md5($left.$password.$right)); | |
return $left.':'.$newpassword.':'.$right; | |
} | |
/** | |
* 验证密码 | |
* | |
* @param {string} $password 待验证的密码 | |
* @param {string} $encrypted 密码加密字符串 | |
* @return {bool} | |
*/ | |
function validatePassword ($password, $encrypted) { | |
$random = explode(':', strtoupper($encrypted)); | |
if (count($random) < 3) return FALSE; | |
$left = $random[0]; | |
$right = $random[2]; | |
$main = $random[1]; | |
$newpassword = strtoupper(md5($left.$password.$right)); | |
return $newpassword == $main; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment