package com.fs.aicall.utils;

import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class AiobPhoneEncryption {

    public static final String CHARSET = "utf-8";
    private static final String AES = "AES";
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    public static void main(String[] args) throws IOException {
        // 电话 密钥
//        System.out.println(encryptAES("15532271587", "426k201008394512"));
    }

    /**
     * 加密
     * plainText 电话号码
     * password 密钥
     */
    public static String encryptAES(String plainText, String password) {
        String cipherText = plainText;
        if (StringUtils.isNotBlank(plainText) && StringUtils.isNotBlank(password)) {
            byte[] cipherBytes = null;
            try {
                cipherBytes = encryptAES(plainText.getBytes(CHARSET), password.getBytes(CHARSET));
            } catch (UnsupportedEncodingException e) {
                throw new BaseException("加密错误");
            }
            cipherText = byte2HexText(cipherBytes);
        }

        return cipherText;
    }

    private static byte[] encryptAES(byte[] plainBytes, byte[] password) {
        byte[] cipherBytes = null;
        try {
            if (plainBytes != null && password != null) {
                SecretKeySpec skeySpec = new SecretKeySpec(password, AES);
                Cipher cipher = Cipher.getInstance(ALGORITHM);
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

                cipherBytes = cipher.doFinal(plainBytes);
            }
        } catch (Exception e) {
            throw new BaseException("加密错误");
        }

        return cipherBytes;
    }

    private static String byte2HexText(byte[] bytes) {
        StringBuilder hexText = new StringBuilder();
        String strTmp;
        for (byte aByte : bytes) {
            strTmp = (Integer.toHexString(aByte & 0XFF));
            if (strTmp.length() == 1) {
                hexText.append("0").append(strTmp);
            } else {
                hexText.append(strTmp);
            }
        }
        return hexText.toString().toUpperCase();
    }

}
