package com.ebts.common.utils.md5;

import com.ebts.common.config.MD5Config;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.DigestUtils;

import java.util.Arrays;
import java.util.Base64;

/**
 * @author: Clay
 * @date: 2022/1/5 15:07
 * @description：IdObfuscator
 * @email: clay@hchyun.com
 */
public class Md5Obfuscator {

    /**
     * 校验等级 1-16,等级越高,密级越高(没什么卵用),encode结果越长
     */
    private static final int VALID_LEVEL = 16;

    /**
     * 编码
     */
    public static String encode(String id){
        byte[] idBytes;
        if (id == null| "".equals(id)){
            return null;
        }
        try {
            idBytes = BytesUtils.long2bytes(Long.parseLong(id));
        }catch (Exception e){
            return id;
        }
        idBytes = BytesUtils.trim(idBytes);
        final byte[] md5 = DigestUtils.md5Digest(ArrayUtils.addAll(idBytes, MD5Config.getSecretKey().getBytes()));
        final byte[] combine = ArrayUtils.addAll(Arrays.copyOf(md5, VALID_LEVEL), idBytes);
        return Base64.getUrlEncoder().encodeToString(combine).replaceAll("=", "");
    }

    /**
     * 解码
     */
    public static String decode(String raw){
        if (raw == null | "".equals(raw)){
            return null;
        }
        final byte[] bytes = Base64.getUrlDecoder().decode(raw);
        final byte[] md5ValidBytes = Arrays.copyOfRange(bytes, 0, VALID_LEVEL);
        final byte[] idBytes = Arrays.copyOfRange(bytes, VALID_LEVEL, bytes.length);
        //验证
        final byte[] md5 = DigestUtils.md5Digest(ArrayUtils.addAll(idBytes, MD5Config.getSecretKey().getBytes()));
        for (int i = 0; i < md5ValidBytes.length; i++) {
            if (md5ValidBytes[i] != md5[i]){
            }
        }

        return String.valueOf(BytesUtils.bytes2Long(idBytes));
    }
}
