package com.xunmei.common.security.utils;


import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * Tkk
 */
@Slf4j
public class SaltHelper {

    private static final String KEY = "rDWBHusbFTlOURS4";

    public static String decryptAES(final String content) {
        try {
            final SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // "算法/模式/补码方式"
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            return new String(cipher.doFinal(Base64.decode(content)));
        } catch (final Exception e) {
//            e.printStackTrace();
            return content;
        }
    }

    public static String encryptAES(final String content) {
        try {
            final SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // "算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            return Base64.encode(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
        } catch (final Exception e) {
//            e.printStackTrace();
            return content;
        }
    }

    /**
     * 比较相等
     *
     * @param src
     * @param give
     * @param salt
     * @return
     */
    public static boolean isEquals(final String src, final String give, final String salt) {
        final String pure = decryptAES(give);
//        log.info("[ {} ] => [ {} ]", give, pure);
        return src.equals(exec(pure, salt));
    }

    /**
     * @param give
     * @param salt
     * @return
     */
    public static String exec(final String give, final String salt) {
        return DigestUtils.md5Hex(give + DigestUtils.md5Hex(salt));
    }

    /**
     * @return
     */
    public static String salt() {
        return DigestUtils.md5Hex(UUID.randomUUID()
                                      .toString());
    }

    public static void main(String[] args) {
       // System.out.println(encryptAES("Admin123456"));
      //  System.out.println(decryptAES("lQTeYH546VVRPTQXS/pcJg=="));
        System.out.println(DigestUtils.md5Hex("6c88ab6be7661b3173455c28e9af1c19"));
        System.out.println(DigestUtils.md5Hex("Admin@123456" + DigestUtils.md5Hex("6c88ab6be7661b3173455c28e9af1c19")));
    }
}
