package com.doghole.mess.test;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptTest {
    
    public static void main(String[] args) {
        try {
            // 设置密钥和初始化向量
            String keyStringBase64 = "5pxlF/NrBtxlBve0jQwGEw=="; // 16字节的密钥
            String ivString = "aesiv_emapp@2018";                // 16字节的初始化向量

            // 要加密的数据
            String plaintext = "xxxxxx";

            // 将密钥和初始化向量转换为字节数组
            byte[] keyBytes = Base64.getDecoder().decode(keyStringBase64);
            byte[] ivBytes = ivString.getBytes(StandardCharsets.UTF_8);

            // 创建密钥和初始化向量对象
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

            // 创建 AES/CBC/PKCS5Padding 加密器
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

            // 执行加密
            byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));

            // 将加密结果转换为Base64字符串
            String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);

            System.out.println("Encrypted String: " + encryptedString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
