package com.siwei.recyclebox.utils;

import android.os.Build;
import android.support.annotation.RequiresApi;

import com.siwei.recyclebox.deviceUtils.ByteUtil;
import com.siwei.recyclebox.ui.main.MainViewModel;
//import org.apache.commons.codec.binary.Base64;

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


import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Log;
import android.util.Base64;
//import org.apache.commons.codec.binary.Base64;
//import org.apache2.commons2.codecdown.binary.Base64;


public class DemoOne {
    @RequiresApi(api = Build.VERSION_CODES.O)

//    private String sKey = "1234567890123456";//key，可自行修改
//    private String ivParameter = "0987654321098765";//偏移量,可自行修改
    public static String encrypt(String encData ,String secretKey,String vector) throws Exception {
        try {
            if (secretKey == null) {
                return null;
            }
            if (secretKey.length() != 16) {
                return null;
            }
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = secretKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
            //return Base64.encodeBase64String(encrypted);
            return Base64.encodeToString(encrypted, Base64.NO_WRAP);// 此处使用BASE64做转码。
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    public static String decrypt(String sSrc,String key,String ivs) throws Exception {
        try {
            byte[] raw = key.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = Base64.decode(sSrc.getBytes(), Base64.NO_WRAP);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }

    public static void main(String[] args) throws Exception {

//        String base64Str = java_openssl_encrypt("{MagDoorSwitch=0, RunningState=1, CurrentTemperature=0, LockSwitch=0, RodSwitch=0, IMEI=, GeoLocation={altitude=523.1, latitude=23.16, longitude=107.31}, Weight=0, RestCapacity=0}", "96e79218965eb72c92a549dd", "1234567891234567");
//        System.out.print("++"+base64Str+"++");
//        Map<String,String> arr = new HashMap<String,String>();
//        arr.put("sss", "1111");
//    public static void main(String[] args) {
//        Map<String,String> arr = new HashMap<String,String>();
//        arr.put("ssss", "11112");
//        StringBuilder data = new StringBuilder("");
//        int k = 0;
//        for (Map.Entry<String, String> entry : arr.entrySet()) {
//            if (k > 0) {
//                data.append("&");
//            }
//            data.append(entry.getKey() + "=" + entry.getValue());
//            k++;
//        }
//        data.append("@");
//        int size = 16;
////        StringBuilder str = new StringBuilder("\0");
//        char[] ascll0 = new char[]{0};
//        char[] ascll7 = new char[]{7};
//        String iv = repeat(new String(ascll0), size);
//        String key = "1111111111111111";
//        int padding = size - data.length() % size;
//        char a = '\u0007';
//        String str2 = String.valueOf(a);
//        String plaintext = data +  repeat(str2, 7);
//        System.out.println(plaintext);
        /*int size = 16;
        char[] ascll0 = new char[]{0};
        String iv = repeat(new String(ascll0), size);
        try {
            String base64Str = DemoOne.encrypt("1213211", "1234567891234567", iv);
//            String base64Str2 = java_openssl_encrypt("{MagDoorSwitch=0, RunningState=1, CurrentTemperature=0, LockSwitch=0, RodSwitch=0, IMEI=, GeoLocation={altitude=523.1, latitude=23.16, longitude=107.31}, Weight=0, RestCapacity=0}", "96e79218965eb72c92a549dd", iv);
            System.out.print("++"+base64Str+"++");
//            String base64Str = java_openssl_encrypt(data.toString(), key);
//            System.out.print(base64Str);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    public static String repeat(String data, int times) {
        StringBuilder str = new StringBuilder(data);
        for (int i = 0; i < times - 1; i++) {
            str.append(data);
        }
        String res = str.toString();
        System.out.println(str.length() + " // " + res.length());
        return res;
    }

   /* public static String java_openssl_encrypt(String data, String password, String iv) throws Exception {
//        byte[] key = new byte[32];

//         * for (int i = 0; i < 32; i++) { if (i < password.getBytes().length) { key[i] =
//         * password.getBytes()[i]; } else { key[i] = 0; } }

//        data = "sss=1111";
//        iv = "1111111111111111";
//        System.out.println("data bytes:"+ByteUtil.bytesToString(data.getBytes()));
//        System.out.println("iv:"+ByteUtil.bytesToString(iv.getBytes()));
//        MessageDigest md5 = MessageDigest.getInstance("MD5");
//        byte[] key = md5.digest(password.getBytes());
//        System.out.println("md5password:"+ ByteUtil.bytesToString(key));
//        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        //加密  pasword  iv 可以定死
//        public static String java_openssl_encrypt (String data, String password) throws Exception {
//            char[] ascll0 = new char[]{0};
//            String iv = repeat(new String(ascll0), 16);
//        MessageDigest md5 = MessageDigest.getInstance("MD5");
//        byte[] key = md5.digest(password.getBytes());

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(password.getBytes(), "AES"),
                    new IvParameterSpec(iv.getBytes("UTF-8")));
//            String base64Str = Base64.encodeBase64String(cipher.doFinal(data.getBytes()));
        String base64Str = Base64.encodeToString(cipher.doFinal(data.getBytes()), Base64.DEFAULT);
            System.out.println(base64Str);
            //解密
            Cipher decryptCipher = Cipher.getInstance("AES/CBC/NoPadding");
            decryptCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(password.getBytes(), "AES"), new IvParameterSpec(iv.getBytes()));
//        byte[] deBytes = decryptCipher.doFinal(Base64.decodeBase64(base64Str));
//        System.out.println(new String(deBytes));
            return base64Str;

        }*/


//        public static String java_openssl_decrypt (String base64Content, String password ) throws
//        Exception {
//            char[] ascll0 = new char[]{0};
//            String iv = repeat(new String(ascll0), 16);
//            Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//            decryptCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(password.getBytes(), "AES"), new IvParameterSpec(iv.getBytes()));
//
//            byte[] deBytes = decryptCipher.doFinal(Base64.decodeBase64(base64Content));
//            String decryptContent = new String(deBytes);
//            return decryptContent;
//
//        }
 /*   public static String java_openssl_dencrypt(String data, String password, String iv) throws Exception {
        //解密
        Cipher decryptCipher = Cipher.getInstance("AES/CBC/NoPadding");
        decryptCipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(password.getBytes(),"AES"),new IvParameterSpec(iv.getBytes()));
        byte[] deBytes = decryptCipher.doFinal(Base64.decodeBase64(data));
        String deByteStr=new String(deBytes);
        return deByteStr;
    }*/

    }
