package com.ruoyi.cai.util;

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

public class AES {

    public static void main(String[] args) throws Exception {
        String jsonData ="zTmtrzE4t6jFriRIde3X+AFG9PQPSTQb5GrZcsBZySFUne3NGpRbb19LUbcKKLaRXj31TSE6nrVz3jLD7nCH+ArJzZwEgMb3hLXZPh53Xluk1Rkq/8wUMsDhAWjPRG012dhoaINUggAJwDKvKDqRgA==";
//        String jsonData = "123";
        String key = "K2AwvosrwtoAgOEP";
        String encod = encrypt(jsonData, key);
        System.out.println(decrypt(jsonData,key));
    }

    public static String encrypt(String data, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String data,String key) throws Exception{
        byte[] decode = Base64.getDecoder().decode(data);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(decode);
        return new String(encryptedBytes,StandardCharsets.UTF_8);

    }
}
