我们还进行了md5密码扩展,这也要在Security框架进行配置,在表中插入一些信息,就可以进行数据库验证了,此时Security框架的配置如下,修改认证管理器:
- <security:authentication-manager>
- <security:authentication-provider>
- <security:password-encoder ref="md5Encoder" />
- <security:jdbc-user-service data-source-ref="dataSource" />
- </security:authentication-provider>
- </security:authentication-manager>
这里我们配置了jdbc数据源和密码编码器,因为连MD5加密方式也是我们自定义的,这样安全系数更高。要使用自定义的加密器,别忘了编写加密器的bean。
加密器类需要实现PasswordEncoder接口,然后编写我们自己的加密方案,加密器很简单,如下设计:
- package org.ourpioneer.board.util;
- import org.springframework.dao.DataAccessException;
- import org.springframework.security.authentication.encoding.PasswordEncoder;
- public class MD5Encoder implements PasswordEncoder {
- public String encodePassword(String origPwd, Object salt)
- throws DataAccessException {
- return MD5.getMD5ofStr(origPwd);
- }
- public boolean isPasswordValid(String encPwd, String origPwd, Object salt)
- throws DataAccessException {
- return encPwd.equals(encodePassword(origPwd, salt));
- }
- }
其中使用到的MD5加密类为:
- package org.ourpioneer.board.util;
- import java.security.MessageDigest;
- public class MD5 {
- public static String getMD5ofStr(String origString) {
- String origMD5 = null;
- try {
- MessageDigest md5 = MessageDigest.getInstance("MD5");
- byte[] result = md5.digest(origString.getBytes());
- origMD5 = byteArray2HexStr(result);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return origMD5;
- }
- private static String byteArray2HexStr(byte[] bs) {
- StringBuffer sb = new StringBuffer();
- for (byte b : bs) {
- sb.append(byte2HexStr(b));
- }
- return sb.toString();
- }
- private static String byte2HexStr(byte b) {
- String hexStr = null;
- int n = b;
- if (n < 0) {
- // 若需要自定义加密,请修改这个移位算法即可
- n = b & 0x7F + 128;
- }
- hexStr = Integer.toHexString(n / 16) + Integer.toHexString(n % 16);
- return hexStr.toUpperCase();
- }
- public static String getMD5ofStr(String origString, int times) {
- String md5 = getMD5ofStr(origString);
- for (int i = 0; i < times - 1; i++) {
- md5 = getMD5ofStr(md5);
- }
- return getMD5ofStr(md5);
- }
- public static boolean verifyPassword(String inputStr, String MD5Code) {
- return getMD5ofStr(inputStr).equals(MD5Code);
- }
- public static boolean verifyPassword(String inputStr, String MD5Code,
- int times) {
- return getMD5ofStr(inputStr, times).equals(MD5Code);
- }
- public static void main(String[] args) {
- System.out.println("123:" + getMD5ofStr("123"));
- System.out.println("123456789:" + getMD5ofStr("123456789"));
- System.out.println("pioneer:" + getMD5ofStr("pioneer"));
- System.out.println("123:" + getMD5ofStr("123", 4));
- }
- }