package com.org.system.config.security;

import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;

@Slf4j
public class Md5PasswordEncoder implements PasswordEncoder {

    private String salt;

    public void setSalt(String salt) {
        this.salt = salt;
    }

    private static Md5PasswordEncoder instance = new Md5PasswordEncoder();

    private Md5PasswordEncoder() {
    }
    //以单例模式构造
    public static Md5PasswordEncoder getInstance() {
        return instance;
    }

    // 用户密码加盐
    private String mergePasswordAndSalt(CharSequence password) {
        if (password == null) password = "";

        if ((salt == null) || "".equals(salt)) {
            return password.toString();
        } else {
            return password + salt;
        }
    }

    /**
     * MD5加密
     *
     * @param rawPassword 原始密码
     * @return 加密后的md5密文
     */
    @Override
    public String encode(CharSequence rawPassword) {

        String result = null;
        try {
            String passwordAndSalt = mergePasswordAndSalt(rawPassword);

            result = SecureUtil.md5(passwordAndSalt);
        } catch (Exception ignored) {

        }
        return result;
    }

    /**
     * 密码比较
     *
     * @param rawPassword     原始密码
     * @param encodedPassword 加密后的密码
     * @return boolean
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encodedPassword.equalsIgnoreCase(encode(rawPassword));
    }
}
