J2SE在java.security.MessageDigest提供了一個(gè)MD5、SHA摘要計(jì)算類。
結(jié)合javascript的md5計(jì)算,可以實(shí)現(xiàn)前臺(tái)口令加密,后臺(tái)數(shù)據(jù)庫(kù)中也保存的是md5或者sha的密碼加密摘要。
具體實(shí)現(xiàn)如下:
1、login.jsp部分
...
<script type="text/javascript" src='js/md5.js'>
</script>
<html:form action="/login" focus="userid" >
<table class="SubFormStyle">
<tr align=left>
<td><bean:message key="caption.LOGIN.UserID" /> <html:text
property="userid" value=""></html:text></td>
<td><bean:message key="caption.LOGIN.Password" /> <html:password
property="passwordinput" value=""></html:password>
<html:hidden
property="password" value="" ></html:hidden></td>
<td><html:submit onclick="password.value = hex_md5(passwordinput.value);">
<bean:message key="button.Login" />
</html:submit></td>
</tr>
</table>
</html:form>
...
2、我用的是struts,具體的action和form就不再浪費(fèi)紙張了,我定義了一個(gè)loginuser的類來(lái)進(jìn)行用戶密碼校驗(yàn),這里只給出校驗(yàn)的方法:
/**
*
* 校驗(yàn)密碼,密碼采用MD5算法加密。
*
* @Param PasswordInput, 待校驗(yàn)密碼
* @Return 校驗(yàn)通過(guò)返回true,否則返回false
*
*
*/
public boolean CheckPassword(String PasswordInput) throws ATError {
this.select();//從數(shù)據(jù)庫(kù)中讀取用戶信息
MessageDigest md;
try {
//生成一個(gè)MD5加密計(jì)算摘要
md = MessageDigest.getInstance("MD5");
//計(jì)算md5函數(shù)
md.update(this.password.getBytes());
//digest()最后確定返回md5 hash值,返回值為8為字符串。因?yàn)閙d5 hash值是16位的hex值,實(shí)際上就是8位的字符
//BigInteger函數(shù)則將8位的字符串轉(zhuǎn)換成16位hex值,用字符串來(lái)表示;得到字符串形式的hash值
String pwd = new BigInteger(1, md.digest()).toString(16);
if (PasswordInput.equals(pwd)) {
return true;
} else {
return false;
}
} catch (NoSuchAlgorithmException e) {
throw new ATError(e, "LoginUser", "CheckPassword", 1000);
}
}
md5.js下載:http://pajhome.org.uk/crypt/md5/index.html
posted on 2006-01-19 09:13
J2EE 閱讀(4287)
評(píng)論(3) 編輯 收藏