Spring security3的MD5加密和StandardPasswordEncoder的配置详解

1、MD5加盐值进行加密处理

application-security.xml文件配置:


        
        	
        		
        	
        
    
直接配置 hash = 'md5' 等效于单独配置

这样,登录时输入的用户密码将会使用md5(加盐值)加密后与数据库里的密文进行匹配。
对应的MD5加密和匹配Java代码:

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
private static final Md5PasswordEncoder md5encoder = new Md5PasswordEncoder();
public static String md5encode(String rawPass, String salt) {
        return md5encoder.encodePassword(rawPass, salt);
    }
    
    public static boolean md5match(String encPass, String rawPass, String salt) { 
    	return md5encoder.isPasswordValid(encPass, rawPass, salt);
    }

2、Spring security3新的StandardPasswordEncoder 标准加密方式

application-security.xml文件配置:


		 //注意这里的秘钥值
	

        
        	
        
    

对应的加密和匹配Java代码:

private static final PasswordEncoder encoder = new StandardPasswordEncoder("my-secret-key");//秘钥值
    
    public static String encrypt(String rawPassword) {
         return encoder.encode(rawPassword);
    }
 
    public static boolean match(String rawPassword, String password) {
         return encoder.matches(rawPassword, password);
    }

盐值不需要用户提供,每次随机生成;多重加密——迭代SHA算法+密钥+随机盐来对密码加密,大大增加密码破解难度,加密后得到的密码是80位。
注意这里的秘钥配置,不配置秘钥也是可以的。

附:StandardPasswordEncoder.java源码中的构造函数:

/**
     * Constructs a standard password encoder with no additional secret value.
     */
public StandardPasswordEncoder() {
        this("");
    }

    /**
     * Constructs a standard password encoder with a secret value which is also included in the
     * password hash.
     *
     * @param secret the secret key used in the encoding process (should not be shared)
     */
    public StandardPasswordEncoder(CharSequence secret) {
        this("SHA-256", secret);
    }

    // internal helpers
    private StandardPasswordEncoder(String algorithm, CharSequence secret) {
        this.digester = new Digester(algorithm, DEFAULT_ITERATIONS);
        this.secret = Utf8.encode(secret);
        this.saltGenerator = KeyGenerators.secureRandom();
    }


你可能感兴趣的:(spring框架)