package com.bcxin.ins.third.gzzrx.taibao.util;


import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import org.apache.commons.codec.binary.Base64;

public class AESUtilsn {
     private static String AESkey() throws Exception{
         KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
         keygenerator.init(128);
         SecretKey generateKey = keygenerator.generateKey();
         byte[] encode = generateKey.getEncoded();
         String encodeHesString = Base64.encodeBase64String(encode);
         encodeHesString = encodeHesString.replace("\r\n", "");
         return encodeHesString;
     }

     public static String encrypt(String message, String key) throws Exception{
         byte[] keyByte = Base64.decodeBase64(key.getBytes("UTF-8"));
         byte[] messageByte = message.getBytes("UTF-8");
         byte[] encryptResult = AesEcbPKCS7PaddingUtils
                 .encrypt(messageByte, keyByte, "AES/ECB/PKCS7Padding");
         message = new String(Base64.encodeBase64(encryptResult));
         return message;
     }

    public static String decrypt(String message, String key) throws Exception{
         byte[] keyByte = Base64.decodeBase64(key.getBytes("UTF-8"));
         byte[] messageByte = Base64.decodeBase64(message.getBytes("UTF-8"));
         byte[] decryptResult = AesEcbPKCS7PaddingUtils
                 .decrypt(messageByte, keyByte, "AES/ECB/PKCS7Padding");
         message = new String(decryptResult, "UTF-8");
        return message;
     }

     public static void main(String[] args) throws Exception {
//         测试 O0r5rx8PY5U76vBmZ/5R/Q==
//         生产 sJaKZsO2IwyToLPhK07kGA==

//         String aesKey = AESkey();//���� AES KEY
         String aesKey = "O0r5rx8PY5U76vBmZ/5R/Q==";
         System.out.println(aesKey);

//         byte[] key = Base64.decodeBase64(aesKey.getBytes("UTF-8"));


         String sourceMessage = "{\"partnerCode\":\"91310115MA1K3TAY4A\",\"transactionCode\":\"300001\",\"messageId\":\"26edba8d-bed3-f0ee-9f28-9b3476e19c2f\",\"transactionEffectiveDate\":\"2023-09-11 14:21:45\",\"user\":\"太平洋保险\"}";
         System.out.println("明文："+sourceMessage);

//         byte[] encryptResult = AesEcbPKCS7PaddingUtils
//                 .encrypt(sourceMessage.getBytes("UTF-8"), key, "AES/ECB/PKCS7Padding");
         sourceMessage = encrypt(sourceMessage,aesKey);

         System.out.println("密文："+sourceMessage);
         System.out.println("比对：P6o19OxA7qoIZAB9xu6R510NS51PDPVjPZdoRsZHvR6zFkiRUXUjH5fgp1n5BImYSQ1NksF19XgecDBJV2aTgfOvvhL+NB0Ub4u0lrwV+KbVpK0mh0GM7/3iYCPiBOjD//+ic1hmGKy333eHeYvR+NqTFXhXktwM2gEQGB/f2BW248LdrRvDHkklB5P0QC+g42mkeirIok8m99weT/3FB4lLtAAUP2Cb8G7cJpnRLt28qFmTIXYJ4V+alS2ft+FW");

         //����

//        byte[] decryptResult = AesEcbPKCS7PaddingUtils
//                .decrypt(Base64.decodeBase64(sourceMessage.getBytes("UTF-8")), key, "AES/ECB/PKCS7Padding");
        sourceMessage = decrypt(sourceMessage,aesKey);
         System.out.println("解密："+sourceMessage);
    }
}
