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" > </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();//秘钥值 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(); }
推荐使用用标准的,不用salt盐值,每次生成的密码都不同,但都能验证通过。