package com.zm.order.tool.server.cipher;


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

/**
 * @Description 新的基于AES的加解密算法
 * @Author: ph
 * @Date: 2022/10/31 15:21
 */
public class AesEncrypt {

    private static byte[] secretKey = createSecretKey();

    private final static String AES_KEY = "23d35a80ffb593bf";

    /**
     * 加密
     *
     * @param plaintext
     * @return
     */
    public static String encrypt(final String plaintext) {
        if (null == plaintext) {
            return null;
        }
        try {
            byte[] result = getCipher(Cipher.ENCRYPT_MODE).doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(result);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 解密
     * @param ciphertext
     * @return
     */
    public static String decrypt(final String ciphertext) {
        if (null == ciphertext) {
            return null;
        }
        try {
            byte[] result = getCipher(Cipher.DECRYPT_MODE).doFinal(Base64.getDecoder().decode(ciphertext));
            return new String(result, StandardCharsets.UTF_8);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private static Cipher getCipher(final int decryptMode) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        Cipher result = Cipher.getInstance("AES/ECB/PKCS5Padding");
        result.init(decryptMode, new SecretKeySpec(secretKey, "AES"));
        return result;
    }

    private static byte[] createSecretKey() {
        return AES_KEY.getBytes(StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        String text = "18846115604";
        String string = AesEncrypt.encrypt(text);
        System.out.println("密文：" + string);
        string = AesEncrypt.decrypt(string);
        System.out.println("明文：" + string);
    }

}
