package com.lemonhc.mplus.framework.util.encription;


import android.util.Base64;
//import sun.misc.BASE64Decoder;

import android.util.Log;

import java.net.URLEncoder;

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


/**
 * Created by kangsh on 2017. 1. 18..
 */

public class AES {

    private static String encriptionKey = "3c837d501a8f49b1";
    private static String message = "eng";


    public static String Decrypt(String text) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        byte[] keyBytes = new byte[16];
        byte[] b = encriptionKey.getBytes("UTF-8");
        int len = b.length;
        if (len > keyBytes.length) len = keyBytes.length;
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

//        Base64 decoder = new Base64();

        text = URLEncoder.encode(text, "UTF-8");
//        text = Base64.encode(text.getBytes(), Base64.DEFAULT);


        byte [] results = Base64.decode(text.getBytes("UTF-8"), Base64.DEFAULT);
        String decode = new String(results,"UTF-8");

        Log.i("복호화 >>>>>>>>>>>", decode);

        return decode;

    }

    public static String Encrypt(String text) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] keyBytes = new byte[16];
        byte[] b = encriptionKey.getBytes("UTF-8");
        int len = b.length;
        if (len > keyBytes.length) len = keyBytes.length;
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

        byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
//               BASE64Encoder encoder = new BASE64Encoder();
//               return encoder.encode(results);


        String result = Base64.encodeToString(results, Base64.DEFAULT);
        Log.i("암호화 =", result);

        return result;
    }

}
