package com.sunyard.config.security;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sunyard.ssp.common.constant.CommonConstant;
import com.sunyard.ssp.utils.sm3.SM3Digest;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @Auther: wp
 * @Date: 2021/12/16 10:47
 * @Description:
 */
public class SM3PasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence rawPassword) {
        String salt = RandomUtil.randomString(CommonConstant.SALT_NUMBER);
        String encode = SM3Digest.encode(salt + rawPassword.toString());
        return new StringBuilder().append(encode).append("@").append(salt).toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if(StrUtil.isBlank(encodedPassword)){
            return false;
        }
        //先从encodedPassword提取salt
        String salt = encodedPassword.split("@")[1];
        String encode = SM3Digest.encode(salt + rawPassword.toString());
        String origin = new StringBuilder().append(encode).append("@").append(salt).toString();

        return MessageDigest.isEqual(origin.getBytes(StandardCharsets.UTF_8), encodedPassword.getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public boolean upgradeEncoding(String encodedPassword) {
        return false;
    }

//    public static void main(String[] args) {
////        String rawPassword="wp123456.";
////        String encode1 = SM3Digest.encode(rawPassword);
////        System.out.println(encode1);
////        String salt = RandomUtil.randomString(CommonConstant.SALT_NUMBER);
////        String encode = SM3Digest.encode(salt + encode1);
////        String s = new StringBuilder().append(encode).append("@").append(salt).toString();
////        System.out.println(s);
//
//        String encodedPassword="00513D5AC7477E6E8FD33A2A6EAAB2F6C04B260DA91E7E6648E8472E914939EB@2sszbadwg5";
//        //AE2B659E60E130E47D18F95387B599E7C261275902020F1D942BD69C2840F28F@tpgb0tfqxc
//        //先从encodedPassword提取salt
//        String salt = encodedPassword.split("@")[1];
//        String rawPassword="3160FD1B6DAEA5A455C7F6C2DC48BEA3A2B9DA73270960791FDBFD60B57A95EA";
//        String encode = SM3Digest.encode(salt + rawPassword.toString());
//        String origin = new StringBuilder().append(encode).append("@").append(salt).toString();
//
//        boolean equal = MessageDigest.isEqual(origin.getBytes(StandardCharsets.UTF_8), encodedPassword.getBytes(StandardCharsets.UTF_8));
//        System.out.println(equal);
//    }

}

