package com.cirle.scientific.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;

/**
 * 身份证号码加密解密器
 */
@Component
public class IdentificationNumberEncryptor {

    /**
     * 加密解密处理所使用的密码
     */
    private final String key;
    private final Cipher encryptCipher;
    private final Cipher decryptCipher;

    public IdentificationNumberEncryptor(@Value("${qkyxzx.utils.identification-number-encryptor.key}") String key) {
        this.key = key;
        encryptCipher = initCipher(Cipher.ENCRYPT_MODE);
        decryptCipher = initCipher(Cipher.DECRYPT_MODE);
    }

    private Cipher initCipher(int mode) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(mode, new SecretKeySpec(key.getBytes(StandardCharsets.US_ASCII), "AES"));
            return cipher;
        } catch (GeneralSecurityException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 身份证号码加密
     *
     * @param plaintextIdentificationNumber 明文身份证号码
     * @return 加密后的身份证号码
     */
    public String encrypt(String plaintextIdentificationNumber) {
        try {
            byte[] encryptedData = encryptCipher.doFinal(plaintextIdentificationNumber.getBytes());
            return Base64.getEncoder().encodeToString(encryptedData);
        } catch (GeneralSecurityException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 身份证号码解密
     *
     * @param encryptedIdentificationNumber 已加密的身份证号码
     * @return 解密后的身份证号码
     */
    public String decrypt(String encryptedIdentificationNumber) {
        try {
            if(StringUtils.isBlank(encryptedIdentificationNumber)){
                return Strings.EMPTY;
            }
            byte[] decryptedData = Base64.getDecoder().decode(encryptedIdentificationNumber);
            return new String(decryptCipher.doFinal(decryptedData));
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
}
