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

来源:互联网 发布:linux启动svn服务命令 编辑:程序博客网 时间:2024/06/03 16:26

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

application-security.xml文件配置:

<authentication-manager>        <authentication-provider>        <password-encoder hash="md5" >        <salt-source user-property="username" />        </password-encoder>        </authentication-provider>    </authentication-manager>
直接配置 hash = 'md5' 等效于单独配置
<bean id="encoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
这样,登录时输入的用户密码将会使用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文件配置:

<bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder" ><constructor-arg name="secret" value="my-secret-key" /> //注意这里的秘钥值</bean><authentication-manager>        <authentication-provider user-service-ref="userExtendService">        <password-encoder ref="encoder" />        </authentication-provider>    </authentication-manager>

对应的加密和匹配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();    }


2 0