package cn.iocoder.yudao.module.system.util.aes;

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

public class AESEncryptionUtil {
    private static final String AES_ALGORITHM = "AES";

    /**
     * 加密
     * @param plaintext
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt(String plaintext, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密
     * @param ciphertext
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt(String ciphertext, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        String plaintext = "Hello, World!2333333333";
        String key = "1234567890abcdef";

        String encryptedText = encrypt(plaintext, key);
        System.out.println("Encrypted Text: " + encryptedText);

        String decryptedText = decrypt(encryptedText, key);
        System.out.println("Decrypted Text: " + decryptedText);
    }

    /**
     * 获取解密后数据
     * @param str
     * @param cameraSecretKey
     * @return
     */
    public static String getEncrypt(String str, String cameraSecretKey){
        try {
            AESEncryptionUtil.decrypt(str, cameraSecretKey);
            return str;
        } catch (Exception ignored) {

        }

        try {
            return AESEncryptionUtil.encrypt(str, cameraSecretKey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
