View Javadoc
1   package cn.home1.oss.lib.security.crypto;
2   
3   import static org.apache.commons.lang3.StringUtils.isNotBlank;
4   
5   import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
6   import org.springframework.security.crypto.password.PasswordEncoder;
7   
8   import java.security.SecureRandom;
9   
10  /**
11   * Created by zhanghaolun on 16/7/8.
12   */
13  public class ReentrantBCryptPasswordEncoder implements PasswordEncoder {
14  
15    private static final char FIELD_SEPERATOR = '$';
16    private final BCryptPasswordEncoder delegate;
17  
18    public ReentrantBCryptPasswordEncoder() {
19      this(-1);
20    }
21  
22    /**
23     * constructor with strength.
24     * 
25     * @param strength the log rounds to use
26     */
27    public ReentrantBCryptPasswordEncoder(final int strength) {
28      this(strength, null);
29    }
30  
31    /**
32     * constructor with strength and random.
33     * 
34     * @param strength the log rounds to use
35     * @param random the secure random instance to use
36     */
37    public ReentrantBCryptPasswordEncoder(final int strength, final SecureRandom random) {
38      this.delegate = new BCryptPasswordEncoder(strength, random);
39    }
40  
41    public static Boolean isBCryptEncoded(final CharSequence encodedPassword) {
42      return isNotBlank(encodedPassword) && encodedPassword.length() == 60
43          && encodedPassword.charAt(0) == FIELD_SEPERATOR
44          && encodedPassword.charAt(3) == FIELD_SEPERATOR
45          && encodedPassword.charAt(6) == FIELD_SEPERATOR;
46    }
47  
48    @Override
49    public String encode(final CharSequence rawPassword) {
50      return this.isEncoded(rawPassword) ? (rawPassword != null ? rawPassword.toString() : null)
51          : this.delegate.encode(rawPassword);
52    }
53  
54    @Override
55    public boolean matches(final CharSequence rawPassword, final String encodedPassword) {
56      return this.delegate.matches(rawPassword, encodedPassword);
57    }
58  
59    public boolean isEncoded(final CharSequence encodedPassword) {
60      return isBCryptEncoded(encodedPassword);
61    }
62  }