安怡的相公

前面有光

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

           上一篇也是介绍security 关于密码方面的,后来文档提过,可以通过password-encoderref属性指定一个自定义的密码编码器bean。这应该包含application context中一个bean的名字,它应该是Spring Security的PasswordEncoder接口的一个实例。

            这个实现总体分三步:

1 、弄一个自己的加密类  这里给出java里的MD5加密算法,copy的。别的还有base64(好像jdk自己就有这个加密算法)

package com.xinma.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.springframework.stereotype.Component;

@Component(
"MD5")
public class MD5 {
public String str;

public String md5s(String plainText) {
try {
MessageDigest md
= MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();

int i;

StringBuffer buf
= new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i
= b[offset];
if (i < 0)
i
+= 256;
if (i < 16)
buf.append(
"0");
buf.append(Integer.toHexString(i));
}
str
= buf.toString();
//System.out.println("result: " + buf.toString());// 32位的加密
return buf.toString();
// System.out.println("result: " + buf.toString().substring(8,
// 24));// 16位的加密
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error";
}
}

}

2. 创建 一个spring的bean 并且把MD5这个类注入,并且写出判断的logic(我是用注解方式注入的)。

package com.xinma.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component(
"MyPasswordEncode")
public class MyPasswordEncode implements PasswordEncoder {

private MD5 md5;

@Autowired
public void setMd5(@Qualifier("MD5") MD5 md5) {
this.md5 = md5;
}

/**
* 这个方法供下面的方法isPasswordValid 调用 是用来进行盐加密的
*
*/
public String encodePassword(String rawPass, Object salt) {
String salted
= rawPass + "{" + salt.toString() + "}";
System.out.println(salted);
return md5.md5s(salted);
}

/**
* 这里便是当用户输入用户名密码后security调用的你自己的密码编辑器的方法 encPass 应该是数据库中的值 rawPass 是你输入的密码值
* salt 盐值
*
*/
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {

if (encPass.equals(encodePassword(rawPass, salt))) {

return true;
}
return false;
}

}

3. 将这个密码编辑bean注入到你的 authentication-manager 并且指定盐值。

    <authentication-manager>
<authentication-provider user-service-ref='myUserDetailsService'>
<password-encoder ref="MyPasswordEncode"><salt-source user-property="username"/></password-encoder>
</authentication-provider>
</authentication-manager>

<b:bean id="myUserDetailsService"
class
="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<b:property name="dataSource" ref="dataS" />
</b:bean>

小弟也是刚学,不懂的可以参考,哪里不对的也希望提出意见,:)s

posted on 2011-07-20 15:20  包子先森  阅读(1690)  评论(0编辑  收藏  举报