package com.palacesun.engine.maskingtool;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class AesUtil {
   public static void main(String[] args) {
      String enStr = encrypt("832-17-1672", "832");
      String dedataStr = decrypt("eFbGkJmQkw4i2HtvD7zn4g==", "832");
   }

   public static String encrypt(String content, String password) {
      try {
         KeyGenerator kgen = KeyGenerator.getInstance("AES");
         kgen.init(128, new SecureRandom(password.getBytes()));
         SecretKey secretKey = kgen.generateKey();
         byte[] enCodeFormat = secretKey.getEncoded();
         SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
         Cipher cipher = Cipher.getInstance("AES");
         byte[] byteContent = content.getBytes("utf-8");
         cipher.init(1, key);
         byte[] result = cipher.doFinal(byteContent);
         return (new Base64()).encodeToString(result);
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
   }

   public static String decrypt(String content, String password) {
      try {
         KeyGenerator kgen = KeyGenerator.getInstance("AES");
         kgen.init(128, new SecureRandom(password.getBytes()));
         SecretKey secretKey = kgen.generateKey();
         byte[] enCodeFormat = secretKey.getEncoded();
         SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
         Cipher cipher = Cipher.getInstance("AES");
         cipher.init(2, key);
         byte[] result = cipher.doFinal(Base64.decodeBase64(content));
         return new String(result);
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
   }

   public static String byteToHexString(byte[] bytes) {
      StringBuffer sb = new StringBuffer(bytes.length);

      for(int i = 0; i < bytes.length; ++i) {
         String sTemp = Integer.toHexString(255 & bytes[i]);
         if (sTemp.length() < 2) {
            sb.append(0);
         }

         sb.append(sTemp.toUpperCase());
      }

      return sb.toString();
   }
}
