package com.storlead.framework.common.util.encryptor;

/**
 * @program: sp-salary-system
 * @description:
 * @author: chenkq
 * @create: 2024-05-27 18:41
 */
import cn.hutool.core.util.StrUtil;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AccessKeyEncryptor {

    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128;

    private SecretKey secretKey;

    public AccessKeyEncryptor(String secret) {
        if (StrUtil.isBlank(secret)) {
            secret = "-storlead$209912";
        }
        this.secretKey = new SecretKeySpec(secret.getBytes(), ALGORITHM);
    }

    public static AccessKeyEncryptor getAccessKeyEncryptor(String secret) {
        return new AccessKeyEncryptor(secret);
    }

    /**
     * 加密
     * @param accessKey
     * @return
     * @throws Exception
     */
    public String encrypt(String accessKey) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(accessKey.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        }catch (Exception e) {
            return "";
        }
    }

    /**
     * 解密
     * @param encryptedAccessKey
     * @return
     * @throws Exception
     */
    public String decrypt(String encryptedAccessKey) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedAccessKey);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        }catch (Exception e) {
            return encryptedAccessKey;
        }
    }


    public static void main(String[] args) {
        try {
            String secret = "";
            AccessKeyEncryptor encryptor = new AccessKeyEncryptor(secret);

            String accessKey = "-Chenkq1992";
            System.out.println("Original AccessKey: " + accessKey);

            String encryptedAccessKey = encryptor.encrypt(accessKey);
            System.out.println("Encrypted AccessKey: " + encryptedAccessKey);

            String decryptedAccessKey = encryptor.decrypt(encryptedAccessKey);
            System.out.println("Decrypted AccessKey: " + decryptedAccessKey);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
