/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.commoncore.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.codvision.commoncore.exception.BusinessException;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 登陆密码解密
 *
 * @author hxl
 */
public class DecPwdUtil {

    /**
     * AES数据块长度为128位，IV（偏移量）长度需要为16个字符（ECB模式不用IV）
     * 密钥（SECRET_KEY）根据指定密钥位数分别为16、24、32个字符，IV与密钥超过长度则截取，不足则在末尾填充'\0'补足
     */
    private static final String SECRET_KEY = "8237909036518327";
    private static final String IV = "4a3f824766747c27";

    public static String encryptAes(String password) {
        AES aes = new AES(Mode.CBC, Padding.ZeroPadding, new SecretKeySpec(SECRET_KEY.getBytes(), "AES"), new IvParameterSpec(IV.getBytes()));
        try {
            return Base64.encode(aes.encrypt(password, StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new BusinessException(30001, "密码加密失败！");
        }
    }


    public static String decryptAes(String password) {
        AES aes = new AES(Mode.CBC, Padding.ZeroPadding, new SecretKeySpec(SECRET_KEY.getBytes(), "AES"), new IvParameterSpec(IV.getBytes()));
        try {
            byte[] decrypt = aes.decrypt(Base64.decode(password.getBytes(StandardCharsets.UTF_8)));
            return new String(decrypt, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new BusinessException(30001, "密码解密失败！");
        }
    }

    public static void main(String[] args) {
        System.out.println(encryptAes("Jcpt@2023"));
    }
}
