package com.ifpdos.factorytest.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.SystemProperties;
import android.util.Log;
import com.android.org.bouncycastle.util.encoders.Hex;
import com.cvte.vman.VmanMiddleWare;
import com.cvte.vman.impl.AtCfgControlManager;
import com.cvte.vman.types.EnumKeyType;
import com.ifpdos.Utils.okhttp.OkHttpHelper;
import com.ifpdos.factorytest.ConfigParser;
import com.ifpdos.factorytest.entity.EmptyBody;
import com.ifpdos.factorytest.entity.StringValueBody;
import com.ifpdos.mcusdk.McuCommandList;
import com.seewo.sdk.SDKConfigureHelper;
import com.seewo.sdk.SDKSystemHelper;
import com.seewo.vcommons.constants.SeewoConstants;
import com.seewo.vcommons.data.PropertiesUtils;
import com.seewo.vcommons.helper.StorageHelper;
import com.seewo.vcommons.utils.ShellCommandUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;

/* JADX INFO: loaded from: classes.dex */
public class RkpUtil {
    private static final String GET_DEVICE_CSR_SHELL_CMD = "rkp_factory_extraction_tool --output_format build+csr";
    private static final String GET_DEVICE_CSR_SHELL_CMD_64Bit = "rkp_factory_extraction_tool64 --output_format build+csr";
    private static final int MAC_LEN = 6;
    private static final String RKP_UPLOAD_STATE = "RKP_UPLOAD_STATE";
    private static final String TAG = "RkpUtil";
    private static byte[] key = {-1, 8, -78, 78, McuCommandList.MAIN_MCU_P_VERSION, 34, 78, -128};
    private static Map<String, String> EDLA_LABORATORY_KEY_MAP = new HashMap<String, String>() { // from class: com.ifpdos.factorytest.util.RkpUtil.1
        {
            put("1", "cvte-foxconn-nanjing");
            put(SeewoConstants.KEY_SECOND_BUTTON, "smart-foxconn-nanjing");
            put(SeewoConstants.KEY_THIRD_BUTTON, "cvte-windriver-shenzhen");
        }
    };

    public static String desEncode(String str) {
        try {
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(1, new SecretKeySpec(key, "DES"));
            return new String(Hex.encode(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8))));
        } catch (Exception e) {
            Log.e(TAG, "desEncode: ", e);
            return "";
        }
    }

    public static String desDecode(String str) {
        try {
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(2, new SecretKeySpec(key, "DES"));
            return new String(cipher.doFinal(Hex.decode(str)), StandardCharsets.UTF_8).trim();
        } catch (Exception e) {
            Log.e(TAG, "desDecode: ", e);
            return "";
        }
    }

    public static boolean isURLReachable(String str) {
        try {
            Response responseExecute = new OkHttpClient.Builder().connectTimeout(10L, TimeUnit.SECONDS).readTimeout(10L, TimeUnit.SECONDS).build().newCall(new Request.Builder().url(str).build()).execute();
            try {
                Log.d(TAG, "isURLReachable: response = " + responseExecute);
                boolean zIsSuccessful = responseExecute.isSuccessful();
                if (responseExecute != null) {
                    responseExecute.close();
                }
                return zIsSuccessful;
            } finally {
            }
        } catch (IOException e) {
            Log.e(TAG, "isURLReachable: error", e);
            return false;
        }
    }

    public static boolean isKeyHasBurned() {
        String widevinevKey;
        String attestationKey;
        try {
            if (PropertiesUtils.getProperty("sys.ignore.key.burned", false)) {
                return true;
            }
            if (Build.VERSION.SDK_INT >= 34 && !isNeedUseOldApi()) {
                Log.d(TAG, "isKeyHasBurned: newAttestationKey = " + VmanMiddleWare.getInstance().getBurnKeyCtrl().getBurnKeyVersion(EnumKeyType.KEY_TYPE_ATTESTATION));
                return !r1.isEmpty();
            }
            if (isNeedUseOldApi() || Build.VERSION.SDK_INT < 34) {
                widevinevKey = VmanMiddleWare.getInstance().getAtCfgControl().readWidevinevKey();
                attestationKey = VmanMiddleWare.getInstance().getAtCfgControl().readAttestationKey();
            } else {
                widevinevKey = VmanMiddleWare.getInstance().getBurnKeyCtrl().getBurnKeyVersion(EnumKeyType.KEY_TYPE_ATTESTATION);
                attestationKey = VmanMiddleWare.getInstance().getBurnKeyCtrl().getBurnKeyVersion(EnumKeyType.KEY_TYPE_ATTESTATION);
            }
            Log.d(TAG, "widevineKey: " + widevinevKey);
            Log.d(TAG, "attestationKey: " + attestationKey);
            return (widevinevKey.equals("NULL") || attestationKey.equals("")) ? false : true;
        } catch (Exception e) {
            Log.e(TAG, "get key error", e);
            return false;
        }
    }

    public static boolean isDeviceConnectedToInternet(Context context) {
        ConnectivityManager connectivityManager;
        NetworkInfo activeNetworkInfo;
        return (context == null || (connectivityManager = (ConnectivityManager) context.getSystemService("connectivity")) == null || (activeNetworkInfo = connectivityManager.getActiveNetworkInfo()) == null || !activeNetworkInfo.isConnected()) ? false : true;
    }

    public static String getDeviceSN() {
        return SDKConfigureHelper.I.getMachineSN();
    }

    public static String getRkpUploadState() {
        try {
            StringValueBody stringValueBody = (StringValueBody) OkHttpHelper.getInstance().get("/v1/system/data/RKP_UPLOAD_STATE", StringValueBody.class);
            Log.d(TAG, "getRkpUploadState: " + stringValueBody);
            if (stringValueBody == null) {
                return "not upload";
            }
            return stringValueBody.value;
        } catch (Exception e) {
            Log.e(TAG, "getRkpUploadState: error", e);
            return "not upload";
        }
    }

    public static String getDeviceCsr() {
        try {
            String str = GET_DEVICE_CSR_SHELL_CMD;
            if (Build.VERSION.SDK_INT >= 34 && !isNeedUseOldApi()) {
                str = GET_DEVICE_CSR_SHELL_CMD_64Bit;
            }
            String strTrim = SDKSystemHelper.I.executeShellCommand(str).getMessage().trim();
            Log.d(TAG, "getDeviceCsr: sdkResult = " + strTrim.trim() + "and lenth" + strTrim.trim().length());
            Matcher matcher = Pattern.compile("\\{[^\\}]*\\}").matcher(strTrim);
            while (matcher.find() && Build.VERSION.SDK_INT >= 34) {
                strTrim = matcher.group();
            }
            return strTrim;
        } catch (Exception e) {
            Log.d(TAG, "getDeviceCsr error", e);
            return null;
        }
    }

    public static boolean setRkpUploadState(String str) {
        HashMap map = new HashMap();
        Log.d(TAG, "setRkpUploadState: " + str);
        map.put("value", str);
        OkHttpHelper.getInstance().postSync("/v1/system/data/RKP_UPLOAD_STATE", map, EmptyBody.class);
        return true;
    }

    public static String getOtherDeviceInfo() {
        JSONObject jSONObject = new JSONObject();
        try {
            jSONObject.put("Customer", SystemProperties.get(SeewoConstants.SYSTEM_PROPERTY_FLAVOR_NAME, "null"));
            jSONObject.put("ModelId", SystemProperties.get(SeewoConstants.SYSTEM_PROPERTY_CVT_PRODUCT_MODEL_PERSIST, "null"));
            jSONObject.put("MachineSn", getDeviceSN());
            jSONObject.put("BoardSn", VmanMiddleWare.getInstance().getAtCfgControl().getString(AtCfgControlManager.IDX_BOARD_SN));
            if (Build.VERSION.SDK_INT >= 34 && !isNeedUseOldApi()) {
                jSONObject.put("WidevinevKey", "");
            } else {
                jSONObject.put("WidevinevKey", VmanMiddleWare.getInstance().getAtCfgControl().readWidevinevKey().replace(ShellCommandUtils.COMMAND_LINE_END, "\\n"));
            }
            if (Build.VERSION.SDK_INT >= 34 && !isNeedUseOldApi()) {
                jSONObject.put("AttestationKey", VmanMiddleWare.getInstance().getAtCfgControl().readAttestationKey());
            } else {
                jSONObject.put("AttestationKey", VmanMiddleWare.getInstance().getBurnKeyCtrl().getBurnKeyVersion(EnumKeyType.KEY_TYPE_ATTESTATION));
            }
            jSONObject.put("MacAddress", getMACAddress());
            jSONObject.put("Version", SystemProperties.get(SeewoConstants.SYSTEM_PROPERTY_KEY_MAIN_MACHINE_BUILD_VERSION, "null"));
        } catch (Exception e) {
            Log.e(TAG, "getOtherDeviceInfo: error", e);
        }
        Log.d(TAG, "getOtherDeviceInfo:" + jSONObject);
        return jSONObject.toString();
    }

    protected static String getMACAddress() {
        try {
            String strConvertMacByteToString = convertMacByteToString(VmanMiddleWare.getInstance().getAtCfgControl().getMacByFuncType(2));
            Log.d(TAG, "getValidMAC: " + strConvertMacByteToString);
            return strConvertMacByteToString;
        } catch (Exception e) {
            Log.e(TAG, "getValidMAC: error", e);
            return "";
        }
    }

    public static String convertMacByteToString(byte[] bArr) {
        int[] iArr = new int[6];
        if (bArr == null || bArr.length != 6) {
            return "00:00:00:00:00:00";
        }
        for (int i = 0; i < 6; i++) {
            iArr[i] = bArr[i] & 255;
        }
        StringBuilder sb = new StringBuilder();
        for (int i2 = 0; i2 < 6; i2++) {
            if (iArr[i2] < 16) {
                sb.append("0" + Integer.toHexString(iArr[i2]) + ":");
            } else {
                sb.append(Integer.toHexString(iArr[i2]) + ":");
            }
        }
        return sb.substring(0, sb.length() - 1);
    }

    public static File getCsrFilePath() {
        return new File(StorageHelper.getInstance().getUsbRootPath(), "key_" + SystemProperties.get(SeewoConstants.SYSTEM_PROPERTY_CVT_PRODUCT_MODEL_PERSIST, "null"));
    }

    public static String getLaboratoryKey(String str) {
        return EDLA_LABORATORY_KEY_MAP.get(str);
    }

    private static boolean isNeedUseOldApi() {
        return Build.VERSION.SDK_INT == 35 && ConfigParser.getBoardType().equals("8195");
    }
}
