使用Spring Security 3进行哈希和腌制密码

如何使用Spring Security 3散列密码并加密它们?

程序化的,你可以这样做:

在application-context.xml(在contextConfigLocation下的web.xml中定义)文件中定义bean(此示例使用md5 )。

  

然后自动设置密码编码器:

 @Autowired PasswordEncoder passwordEncoder; 

在您的方法中或您想要哈希和盐的任何地方。

 passwordEncoder.encodePassword("MyPasswordAsString", "mySaltAsStringOrObject"); 

上面的调用应该返回一个salted hash(作为String )。

应该这样做。 我假设你可以找出你需要的jar子。

UPDATE

不言而喻,使用MD5并不是最好的主意。 理想情况下,您应该至少使用SHA-256。 这可以使用ShaPasswordEncoder完成。

将上面的MD5 bean配置替换为:

    

最简单的似乎是Spring Security 3.1假设没有对散列方式的约束:

        @Controller @Stateless public class UsersEJB { @PersistenceContext(unitName = "somePU") private EntityManager em; @Transactional public void create(Users users) { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(users.getPassword()); users.setPassword(hashedPassword); em.persist(users); } } 

最简单的方法,如记录 :

        

HTH