package cn.security.spring.crypto;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import cn.util.codec.EncryKit;
import cn.util.core.TypeKit;

public class PasswordEncoderUtil implements PasswordEncoder
{
	private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();
	
	private String encoder = ""; 
	public PasswordEncoderUtil() {}
	public PasswordEncoderUtil(String encoder) {
		this.encoder = encoder;
	}
	
    @Override
    public String encode(CharSequence rawPassword) {
    	if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }
    	
    	/**自定义密码比较器*/
    	if("MD5".equalsIgnoreCase(encoder)) {
    		return EncryKit.encodeMD5(TypeKit.objToStr(rawPassword));
    	}
    	else if("SHA".equalsIgnoreCase(encoder)) {
    		return EncryKit.encodeAES(TypeKit.objToStr(rawPassword));
    	}
    	//默认
   		return  BCRYPT.encode(rawPassword);
    }
    /**rawPassword 用户输出  encodedPassword库中读出*/
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
    	/**自定义密码比较器*/
    	if("MD5".equalsIgnoreCase(encoder)) {
    		return encodedPassword.equals(EncryKit.encodeMD5(TypeKit.objToStr(rawPassword)));
    	}
    	else if("SHA".equalsIgnoreCase(encoder)) {
    		return encodedPassword.equals(EncryKit.encodeAES(TypeKit.objToStr(rawPassword)));
    	}
    	//默认
   		return BCRYPT.matches(rawPassword,encodedPassword);
    }
}