智能工厂.apk(点击下载) / DeviceId.java


package com.baidu.speech.utils.cuid.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Process;
import android.os.SystemClock;
import android.provider.Settings;
import android.system.ErrnoException;
import android.system.Os;
import android.text.TextUtils;
import android.util.Log;
import androidx.core.view.MotionEventCompat;
import com.baidu.speech.utils.MD5Util;
import com.baidu.speech.utils.cuid.security.AESUtil;
import com.baidu.speech.utils.cuid.security.Base64;
import com.baidu.speech.utils.cuid.security.SHA1Util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import javax.crypto.Cipher;
import org.altbeacon.bluetooth.Pdu;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public final class DeviceId {
    private static final String ACTION_GLAXY_CUID = "com.baidu.intent.action.GALAXY";
    private static final String AES_KEY;
    private static final boolean CONFIG_WRITE_V1_STORAGE = false;
    private static final boolean DEBUG = false;
    private static final String DEFAULT_TM_DEVICEID = "";
    private static final String EXT_DIR = "backups/.SystemConfig";
    private static final String EXT_FILE = ".cuid";
    private static final String EXT_FILE_V2 = ".cuid2";
    private static final String KEY_DEVICE_ID = "com.baidu.deviceid";
    private static final String KEY_DEVICE_ID_V2 = "com.baidu.deviceid.v2";
    private static final String KEY_FLAG = "bd_setting_i";
    private static final String META_KEY_GALAXY_SF = "galaxy_sf";
    private static final String META_KEY_GLAXY_DATA = "galaxy_data";
    private static final String OLD_EXT_DIR = "baidu";
    private static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
    private static final int SDK_ANDROID_M = 23;
    private static final String SELF_CUID_FILE = "libcuid.so";
    private static final int STORAGE_SDCARD_V1 = 4;
    private static final int STORAGE_SDCARD_V2 = 8;
    private static final int STORAGE_SELF_FILE = 16;
    private static final int STORAGE_SYSTEM_SETTING_V1 = 1;
    private static final int STORAGE_SYSTEM_SETTING_V2 = 2;
    private static final int S_IRGRP = 32;
    private static final int S_IROTH = 4;
    private static final int S_IRUSR = 256;
    private static final int S_IRWXG = 56;
    private static final int S_IRWXO = 7;
    private static final int S_IRWXU = 448;
    private static final int S_IWGRP = 16;
    private static final int S_IWOTH = 2;
    private static final int S_IWUSR = 128;
    private static final int S_IXGRP = 8;
    private static final int S_IXOTH = 1;
    private static final int S_IXUSR = 64;
    private static final String TAG = "DeviceId";
    private static CUIDInfo sCachedCuidInfo = null;
    private static final String sDEncoded = "ZGV2aWNlaWQ=";
    private static boolean sDataCuidInfoShable = true;
    private static final String sIEncoded = "aW1laQ==";
    private static final String sVEncoded = "dmVy";
    private final Context mContext;
    private PublicKey mPublicKey;
    private int mSaveMask = 0;

    /* access modifiers changed from: private */
    public static class CUIDBuddyInfo {
        public ApplicationInfo appInfo;
        public boolean isSelf;
        public int priority;
        public boolean sigMatched;

        private CUIDBuddyInfo() {
            this.priority = 0;
            this.sigMatched = false;
            this.isSelf = false;
        }
    }

    /* access modifiers changed from: private */
    public static class CUIDInfo {
        public static final String I_EMPTY = "0";
        public static final String I_FIXED = "O";
        public static final int PROTOCAL_MAX_LENGTH = 14;
        private static final int VERSION_DEF = 2;
        public String deviceId;
        public String flag;
        public int oldValueLength;
        public int version;

        private CUIDInfo() {
            this.version = 2;
            this.oldValueLength = 0;
        }

        /* access modifiers changed from: private */
        public static CUIDInfo createCuidInfoFromV1Cache(String str, String str2) {
            if (TextUtils.isEmpty(str)) {
                return null;
            }
            CUIDInfo cUIDInfo = new CUIDInfo();
            cUIDInfo.deviceId = str;
            cUIDInfo.oldValueLength = TextUtils.isEmpty(str2) ? 0 : str2.length();
            if (cUIDInfo.oldValueLength < 14) {
                if (TextUtils.isEmpty(str2)) {
                    str2 = I_EMPTY;
                }
                cUIDInfo.flag = str2;
            }
            return cUIDInfo;
        }

        public static CUIDInfo createFromJson(String str) {
            if (TextUtils.isEmpty(str)) {
                return null;
            }
            try {
                JSONObject jSONObject = new JSONObject(str);
                Iterator<String> keys = jSONObject.keys();
                String str2 = I_EMPTY;
                while (keys.hasNext()) {
                    String next = keys.next();
                    if (!DeviceId.getBase64DecodeStr(DeviceId.sDEncoded).equals(next)) {
                        if (!DeviceId.getBase64DecodeStr(DeviceId.sVEncoded).equals(next)) {
                            str2 = jSONObject.optString(next, I_EMPTY);
                        }
                    }
                }
                String string = jSONObject.getString(DeviceId.getBase64DecodeStr(DeviceId.sDEncoded));
                int i = jSONObject.getInt(DeviceId.getBase64DecodeStr(DeviceId.sVEncoded));
                int length = TextUtils.isEmpty(str2) ? 0 : str2.length();
                if (!TextUtils.isEmpty(string)) {
                    CUIDInfo cUIDInfo = new CUIDInfo();
                    cUIDInfo.deviceId = string;
                    cUIDInfo.version = i;
                    cUIDInfo.oldValueLength = length;
                    if (cUIDInfo.oldValueLength < 14) {
                        if (TextUtils.isEmpty(str2)) {
                            str2 = I_EMPTY;
                        }
                        cUIDInfo.flag = str2;
                    }
                    return cUIDInfo;
                }
            } catch (JSONException e) {
                DeviceId.handleThrowable(e);
            }
            return null;
        }

        public static boolean isIENormal(int i) {
            return i >= 14;
        }

        public static boolean isIENull(String str) {
            return TextUtils.isEmpty(str);
        }

        public String getFinalCUID() {
            String str = this.flag;
            if (TextUtils.isEmpty(str)) {
                str = I_EMPTY;
            }
            return this.deviceId + "|" + str;
        }

        public boolean isIENormal() {
            return isIENormal(this.oldValueLength);
        }

        public boolean isIENull() {
            return isIENull(this.flag);
        }

        public String toPersitString() {
            try {
                return new JSONObject().put(DeviceId.getBase64DecodeStr(DeviceId.sDEncoded), this.deviceId).put(DeviceId.getBase64DecodeStr(DeviceId.sIEncoded), this.flag).put(DeviceId.getBase64DecodeStr(DeviceId.sVEncoded), this.version).toString();
            } catch (JSONException e) {
                DeviceId.handleThrowable(e);
                return null;
            }
        }
    }

    /* access modifiers changed from: package-private */
    public static class TargetApiSupport {
        TargetApiSupport() {
        }

        @TargetApi(MotionEventCompat.AXIS_WHEEL)
        static boolean doChmodSafely(String str, int i) {
            try {
                Os.chmod(str, i);
                return true;
            } catch (ErrnoException e) {
                DeviceId.handleThrowable(e);
                return false;
            } catch (Exception e2) {
                DeviceId.handleThrowable(e2);
                return false;
            }
        }
    }

    static {
        String str = new String(Base64.decode(new byte[]{77, 122, 65, 121, 77, 84, 73, 120, 77, 68, 73, 61}));
        String str2 = new String(Base64.decode(new byte[]{90, 71, 108, 106, 100, 87, 82, 112, 89, 87, 73, 61}));
        AES_KEY = str + str2;
    }

    private DeviceId(Context context) {
        this.mContext = context.getApplicationContext();
        initPublicKey();
    }

    private static String byte2hex(byte[] bArr) {
        StringBuilder sb;
        if (bArr != null) {
            String str = "";
            for (byte b : bArr) {
                String hexString = Integer.toHexString(b & Pdu.MANUFACTURER_DATA_PDU_TYPE);
                if (hexString.length() == 1) {
                    sb = new StringBuilder();
                    sb.append(str);
                    str = CUIDInfo.I_EMPTY;
                } else {
                    sb = new StringBuilder();
                }
                sb.append(str);
                sb.append(hexString);
                str = sb.toString();
            }
            return str.toLowerCase();
        }
        throw new IllegalArgumentException("Argument b ( byte array ) is null! ");
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private boolean checkSelfPermission(String str) {
        return this.mContext.checkPermission(str, Process.myPid(), Process.myUid()) == 0;
    }

    private List<CUIDBuddyInfo> collectBuddyInfos(Intent intent, boolean z) {
        ArrayList arrayList = new ArrayList();
        PackageManager packageManager = this.mContext.getPackageManager();
        List<ResolveInfo> queryBroadcastReceivers = packageManager.queryBroadcastReceivers(intent, 0);
        if (queryBroadcastReceivers != null) {
            for (ResolveInfo resolveInfo : queryBroadcastReceivers) {
                if (!(resolveInfo.activityInfo == null || resolveInfo.activityInfo.applicationInfo == null)) {
                    try {
                        Bundle bundle = packageManager.getReceiverInfo(new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name), 128).metaData;
                        if (bundle != null) {
                            String string = bundle.getString(META_KEY_GLAXY_DATA);
                            if (!TextUtils.isEmpty(string)) {
                                byte[] decode = Base64.decode(string.getBytes("utf-8"));
                                JSONObject jSONObject = new JSONObject(new String(decode));
                                CUIDBuddyInfo cUIDBuddyInfo = new CUIDBuddyInfo();
                                cUIDBuddyInfo.priority = jSONObject.getInt("priority");
                                cUIDBuddyInfo.appInfo = resolveInfo.activityInfo.applicationInfo;
                                if (this.mContext.getPackageName().equals(resolveInfo.activityInfo.applicationInfo.packageName)) {
                                    cUIDBuddyInfo.isSelf = true;
                                }
                                if (z) {
                                    String string2 = bundle.getString(META_KEY_GALAXY_SF);
                                    if (!TextUtils.isEmpty(string2)) {
                                        PackageInfo packageInfo = packageManager.getPackageInfo(resolveInfo.activityInfo.applicationInfo.packageName, 64);
                                        JSONArray jSONArray = jSONObject.getJSONArray("sigs");
                                        String[] strArr = new String[jSONArray.length()];
                                        for (int i = 0; i < strArr.length; i++) {
                                            strArr[i] = jSONArray.getString(i);
                                        }
                                        if (isSigsEqual(strArr, formatAndroidSigArray(packageInfo.signatures))) {
                                            byte[] decryptByPublicKey = decryptByPublicKey(Base64.decode(string2.getBytes()), this.mPublicKey);
                                            if (decryptByPublicKey != null && Arrays.equals(decryptByPublicKey, SHA1Util.sha1(decode))) {
                                                cUIDBuddyInfo.sigMatched = true;
                                            }
                                        }
                                    }
                                }
                                arrayList.add(cUIDBuddyInfo);
                            }
                        }
                    } catch (Exception unused) {
                    }
                }
            }
        }
        Collections.sort(arrayList, new Comparator<CUIDBuddyInfo>() {
            /* class com.baidu.speech.utils.cuid.util.DeviceId.AnonymousClass1 */

            public int compare(CUIDBuddyInfo cUIDBuddyInfo, CUIDBuddyInfo cUIDBuddyInfo2) {
                int i = cUIDBuddyInfo2.priority - cUIDBuddyInfo.priority;
                if (i == 0) {
                    if (cUIDBuddyInfo.isSelf && cUIDBuddyInfo2.isSelf) {
                        return 0;
                    }
                    if (cUIDBuddyInfo.isSelf) {
                        return -1;
                    }
                    if (cUIDBuddyInfo2.isSelf) {
                        return 1;
                    }
                }
                return i;
            }
        });
        return arrayList;
    }

    private static byte[] decryptByPublicKey(byte[] bArr, PublicKey publicKey) throws Exception {
        Cipher instance = Cipher.getInstance(RSA_ALGORITHM);
        instance.init(2, publicKey);
        return instance.doFinal(bArr);
    }

    /* access modifiers changed from: private */
    public static String decryptCUIDInfo(String str) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            return new String(AESUtil.decrypt(AES_KEY, AES_KEY, Base64.decode(str.getBytes())));
        } catch (Exception e) {
            handleThrowable(e);
            return "";
        }
    }

    /* access modifiers changed from: private */
    public static String encryptCUIDInfo(String str) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            return Base64.encode(AESUtil.encrypt(AES_KEY, AES_KEY, str.getBytes()), "utf-8");
        } catch (UnsupportedEncodingException | Exception e) {
            handleThrowable(e);
            return "";
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private boolean fixCUIDInfoByIE(CUIDInfo cUIDInfo) {
        String str;
        if (cUIDInfo.isIENormal()) {
            str = CUIDInfo.I_FIXED;
        } else if (!cUIDInfo.isIENull()) {
            return false;
        } else {
            str = CUIDInfo.I_EMPTY;
        }
        cUIDInfo.flag = str;
        return true;
    }

    private String[] formatAndroidSigArray(Signature[] signatureArr) {
        String[] strArr = new String[signatureArr.length];
        for (int i = 0; i < strArr.length; i++) {
            strArr[i] = byte2hex(SHA1Util.sha1(signatureArr[i].toByteArray()));
        }
        return strArr;
    }

    private static String getAndroidId(Context context) {
        String string = Settings.Secure.getString(context.getContentResolver(), "android_id");
        return TextUtils.isEmpty(string) ? "" : string;
    }

    /* access modifiers changed from: private */
    public static String getBase64DecodeStr(String str) {
        return new String(Base64.decode(str.getBytes()));
    }

    public static String getCUID(Context context) {
        return getOrCreateCUIDInfo(context).getFinalCUID();
    }

    private CUIDInfo getCUIDInfo() {
        boolean z;
        String str;
        List<CUIDBuddyInfo> collectBuddyInfos = collectBuddyInfos(new Intent(ACTION_GLAXY_CUID).setPackage(this.mContext.getPackageName()), true);
        boolean z2 = false;
        if (collectBuddyInfos == null || collectBuddyInfos.size() == 0) {
            for (int i = 0; i < 3; i++) {
                Log.w("DeviceId", "galaxy lib host missing meta-data,make sure you know the right way to integrate galaxy");
            }
            z = false;
        } else {
            CUIDBuddyInfo cUIDBuddyInfo = collectBuddyInfos.get(0);
            z = cUIDBuddyInfo.sigMatched;
            if (!cUIDBuddyInfo.sigMatched) {
                for (int i2 = 0; i2 < 3; i2++) {
                    Log.w("DeviceId", "galaxy config err, In the release version of the signature should be matched");
                }
            }
        }
        File file = new File(this.mContext.getFilesDir(), SELF_CUID_FILE);
        CUIDInfo createFromJson = file.exists() ? CUIDInfo.createFromJson(decryptCUIDInfo(getFileContent(file))) : null;
        if (createFromJson == null) {
            this.mSaveMask |= 16;
            List<CUIDBuddyInfo> collectBuddyInfos2 = collectBuddyInfos(new Intent(ACTION_GLAXY_CUID), z);
            if (collectBuddyInfos2 != null) {
                String str2 = "files";
                File filesDir = this.mContext.getFilesDir();
                if (!str2.equals(filesDir.getName())) {
                    Log.e("DeviceId", "fetal error:: app files dir name is unexpectedly :: " + filesDir.getAbsolutePath());
                    str2 = filesDir.getName();
                }
                for (CUIDBuddyInfo cUIDBuddyInfo2 : collectBuddyInfos2) {
                    if (!cUIDBuddyInfo2.isSelf) {
                        File file2 = new File(new File(cUIDBuddyInfo2.appInfo.dataDir, str2), SELF_CUID_FILE);
                        if (file2.exists() && (createFromJson = CUIDInfo.createFromJson(decryptCUIDInfo(getFileContent(file2)))) != null) {
                            break;
                        }
                    }
                }
            }
        }
        if (createFromJson == null) {
            createFromJson = CUIDInfo.createFromJson(decryptCUIDInfo(getSystemSettingValue(KEY_DEVICE_ID_V2)));
        }
        boolean checkSelfPermission = checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE");
        if (createFromJson == null && checkSelfPermission) {
            this.mSaveMask |= 2;
            createFromJson = getCuidInfoFromExternalV2();
        }
        if (createFromJson == null) {
            this.mSaveMask |= 8;
            createFromJson = getCUidInfoFromSystemSettingV1();
        }
        if (createFromJson != null || !checkSelfPermission) {
            str = null;
        } else {
            this.mSaveMask |= 1;
            String defaultFlag = getDefaultFlag("");
            z2 = true;
            str = defaultFlag;
            createFromJson = getExternalV1DeviceId(defaultFlag);
        }
        if (createFromJson == null) {
            this.mSaveMask |= 4;
            if (!z2) {
                str = getDefaultFlag("");
            }
            createFromJson = new CUIDInfo();
            String androidId = getAndroidId(this.mContext);
            createFromJson.deviceId = MD5Util.toMd5((Build.VERSION.SDK_INT < 23 ? str + androidId + UUID.randomUUID().toString() : "com.baidu" + androidId).getBytes(), true);
            createFromJson.flag = str;
        }
        fixCUIDInfoByIE(createFromJson);
        writeJobThread(createFromJson);
        return createFromJson;
    }

    private CUIDInfo getCUidInfoFromSystemSettingV1() {
        return CUIDInfo.createCuidInfoFromV1Cache(getSystemSettingValue(KEY_DEVICE_ID), getSystemSettingValue(KEY_FLAG));
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private CUIDInfo getCuidInfoFromExternalV2() {
        File file = new File(Environment.getExternalStorageDirectory(), "backups/.SystemConfig/.cuid2");
        if (!file.exists()) {
            return null;
        }
        String fileContent = getFileContent(file);
        if (TextUtils.isEmpty(fileContent)) {
            return null;
        }
        try {
            return CUIDInfo.createFromJson(new String(AESUtil.decrypt(AES_KEY, AES_KEY, Base64.decode(fileContent.getBytes()))));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private String getDefaultFlag(String str) {
        return CUIDInfo.I_EMPTY;
    }

    public static String getDeviceID(Context context) {
        return getOrCreateCUIDInfo(context).deviceId;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private CUIDInfo getExternalV1DeviceId(String str) {
        String str2 = "";
        String str3 = "";
        File file = new File(Environment.getExternalStorageDirectory(), "baidu/.cuid");
        if (!file.exists()) {
            file = new File(Environment.getExternalStorageDirectory(), "backups/.SystemConfig/.cuid");
        }
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            StringBuilder sb = new StringBuilder();
            while (true) {
                String readLine = bufferedReader.readLine();
                if (readLine == null) {
                    break;
                }
                sb.append(readLine);
                sb.append("\r\n");
            }
            bufferedReader.close();
            String[] split = new String(AESUtil.decrypt(AES_KEY, AES_KEY, Base64.decode(sb.toString().getBytes()))).split("=");
            if (split != null && split.length == 2) {
                str3 = split[0];
                str2 = split[1];
            }
        } catch (FileNotFoundException | IOException | Exception unused) {
        }
        return CUIDInfo.createCuidInfoFromV1Cache(str2, str3);
    }

    /* access modifiers changed from: private */
    /* JADX WARNING: Removed duplicated region for block: B:23:0x0033 A[SYNTHETIC, Splitter:B:23:0x0033] */
    /* JADX WARNING: Removed duplicated region for block: B:30:0x003f A[SYNTHETIC, Splitter:B:30:0x003f] */
    public static String getFileContent(File file) {
        Throwable th;
        FileReader fileReader;
        Exception e;
        try {
            fileReader = new FileReader(file);
            try {
                char[] cArr = new char[8192];
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                while (true) {
                    int read = fileReader.read(cArr);
                    if (read <= 0) {
                        break;
                    }
                    charArrayWriter.write(cArr, 0, read);
                }
                String charArrayWriter2 = charArrayWriter.toString();
                try {
                    fileReader.close();
                } catch (Exception e2) {
                    handleThrowable(e2);
                }
                return charArrayWriter2;
            } catch (Exception e3) {
                e = e3;
                try {
                    handleThrowable(e);
                    if (fileReader != null) {
                    }
                    return null;
                } catch (Throwable th2) {
                    th = th2;
                    if (fileReader != null) {
                    }
                    throw th;
                }
            }
        } catch (Exception e4) {
            e = e4;
            fileReader = null;
            handleThrowable(e);
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (Exception e5) {
                    handleThrowable(e5);
                }
            }
            return null;
        } catch (Throwable th3) {
            th = th3;
            fileReader = null;
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (Exception e6) {
                    handleThrowable(e6);
                }
            }
            throw th;
        }
    }

    private static CUIDInfo getOrCreateCUIDInfo(Context context) {
        if (sCachedCuidInfo == null) {
            synchronized (CUIDInfo.class) {
                if (sCachedCuidInfo == null) {
                    SystemClock.uptimeMillis();
                    sCachedCuidInfo = new DeviceId(context).getCUIDInfo();
                    SystemClock.uptimeMillis();
                }
            }
        }
        return sCachedCuidInfo;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private String getSystemSettingValue(String str) {
        try {
            return Settings.System.getString(this.mContext.getContentResolver(), str);
        } catch (Exception e) {
            handleThrowable(e);
            return null;
        }
    }

    private Runnable getWriteRunnable(final CUIDInfo cUIDInfo) {
        return new Runnable() {
            /* class com.baidu.speech.utils.cuid.util.DeviceId.AnonymousClass2 */

            /* JADX WARNING: Code restructure failed: missing block: B:19:0x009e, code lost:
                if (r2 == null) goto L_0x0074;
             */
            /* JADX WARNING: Code restructure failed: missing block: B:30:0x00d9, code lost:
                if (r3 == null) goto L_0x00bc;
             */
            /* JADX WARNING: Code restructure failed: missing block: B:8:0x005b, code lost:
                if (r1 == null) goto L_0x0031;
             */
            /* JADX WARNING: Removed duplicated region for block: B:11:0x0066  */
            /* JADX WARNING: Removed duplicated region for block: B:22:0x00ab  */
            /* JADX WARNING: Removed duplicated region for block: B:32:0x00de  */
            public void run() {
                boolean hasWriteSettingsPermission;
                boolean checkSelfPermission;
                CUIDInfo externalV1DeviceId;
                DeviceId deviceId;
                String str;
                String str2;
                CUIDInfo cUIDInfo = new CUIDInfo();
                cUIDInfo.flag = cUIDInfo.flag;
                cUIDInfo.deviceId = cUIDInfo.deviceId;
                File file = new File(DeviceId.this.mContext.getFilesDir(), DeviceId.SELF_CUID_FILE);
                String encryptCUIDInfo = DeviceId.encryptCUIDInfo(cUIDInfo.toPersitString());
                if (file.exists()) {
                    CUIDInfo createFromJson = CUIDInfo.createFromJson(DeviceId.decryptCUIDInfo(DeviceId.getFileContent(file)));
                    if (createFromJson != null) {
                        if (DeviceId.this.fixCUIDInfoByIE(createFromJson)) {
                            DeviceId.this.writeToCuidFile(DeviceId.encryptCUIDInfo(createFromJson.toPersitString()));
                        }
                    }
                    hasWriteSettingsPermission = DeviceId.this.hasWriteSettingsPermission();
                    if (hasWriteSettingsPermission) {
                        String systemSettingValue = DeviceId.this.getSystemSettingValue(DeviceId.KEY_DEVICE_ID_V2);
                        if (!TextUtils.isEmpty(systemSettingValue)) {
                            CUIDInfo createFromJson2 = CUIDInfo.createFromJson(DeviceId.decryptCUIDInfo(systemSettingValue));
                            if (createFromJson2 != null) {
                                if (DeviceId.this.fixCUIDInfoByIE(createFromJson2)) {
                                    DeviceId.this.tryPutSystemSettingValue(DeviceId.KEY_DEVICE_ID_V2, DeviceId.encryptCUIDInfo(createFromJson2.toPersitString()));
                                }
                            }
                        }
                        DeviceId.this.tryPutSystemSettingValue(DeviceId.KEY_DEVICE_ID_V2, encryptCUIDInfo);
                    }
                    checkSelfPermission = DeviceId.this.checkSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE");
                    if (checkSelfPermission) {
                        if (new File(Environment.getExternalStorageDirectory(), "backups/.SystemConfig/.cuid2").exists()) {
                            CUIDInfo cuidInfoFromExternalV2 = DeviceId.this.getCuidInfoFromExternalV2();
                            if (cuidInfoFromExternalV2 != null) {
                                if (DeviceId.this.fixCUIDInfoByIE(cuidInfoFromExternalV2)) {
                                    encryptCUIDInfo = DeviceId.encryptCUIDInfo(cuidInfoFromExternalV2.toPersitString());
                                }
                            }
                        }
                        DeviceId.setExternalV2DeviceId(encryptCUIDInfo);
                    }
                    if (hasWriteSettingsPermission) {
                        String systemSettingValue2 = DeviceId.this.getSystemSettingValue(DeviceId.KEY_FLAG);
                        if (CUIDInfo.isIENormal(TextUtils.isEmpty(systemSettingValue2) ? 0 : systemSettingValue2.length())) {
                            deviceId = DeviceId.this;
                            str = DeviceId.KEY_FLAG;
                            str2 = CUIDInfo.I_FIXED;
                        } else if (CUIDInfo.isIENull(systemSettingValue2)) {
                            deviceId = DeviceId.this;
                            str = DeviceId.KEY_FLAG;
                            str2 = CUIDInfo.I_EMPTY;
                        }
                        deviceId.tryPutSystemSettingValue(str, str2);
                    }
                    if (checkSelfPermission && new File(Environment.getExternalStorageDirectory(), "backups/.SystemConfig/.cuid").exists() && (externalV1DeviceId = DeviceId.this.getExternalV1DeviceId(DeviceId.this.getDefaultFlag(""))) != null && DeviceId.this.fixCUIDInfoByIE(externalV1DeviceId)) {
                        DeviceId.setExternalDeviceId(externalV1DeviceId.flag, externalV1DeviceId.deviceId);
                        return;
                    }
                    return;
                }
                DeviceId.this.writeToCuidFile(encryptCUIDInfo);
                hasWriteSettingsPermission = DeviceId.this.hasWriteSettingsPermission();
                if (hasWriteSettingsPermission) {
                }
                checkSelfPermission = DeviceId.this.checkSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE");
                if (checkSelfPermission) {
                }
                if (hasWriteSettingsPermission) {
                }
                if (checkSelfPermission) {
                }
            }
        };
    }

    /* access modifiers changed from: private */
    public static void handleThrowable(Throwable th) {
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private boolean hasWriteSettingsPermission() {
        return checkSelfPermission("android.permission.WRITE_SETTINGS");
    }

    /* JADX WARNING: Removed duplicated region for block: B:14:0x002b A[SYNTHETIC, Splitter:B:14:0x002b] */
    /* JADX WARNING: Removed duplicated region for block: B:23:0x0037  */
    /* JADX WARNING: Removed duplicated region for block: B:26:? A[RETURN, SYNTHETIC] */
    private void initPublicKey() {
        ByteArrayInputStream byteArrayInputStream;
        Throwable th;
        try {
            byteArrayInputStream = new ByteArrayInputStream(CuidCertStore.getCertBytes());
            try {
                this.mPublicKey = CertificateFactory.getInstance("X.509").generateCertificate(byteArrayInputStream).getPublicKey();
                try {
                    byteArrayInputStream.close();
                } catch (Exception e) {
                    handleThrowable(e);
                }
            } catch (Exception unused) {
                if (byteArrayInputStream == null) {
                    byteArrayInputStream.close();
                }
            } catch (Throwable th2) {
                th = th2;
                if (byteArrayInputStream != null) {
                    try {
                        byteArrayInputStream.close();
                    } catch (Exception e2) {
                        handleThrowable(e2);
                    }
                }
                throw th;
            }
        } catch (Exception unused2) {
            byteArrayInputStream = null;
            if (byteArrayInputStream == null) {
            }
        } catch (Throwable th3) {
            byteArrayInputStream = null;
            th = th3;
            if (byteArrayInputStream != null) {
            }
            throw th;
        }
    }

    private boolean isSigsEqual(String[] strArr, String[] strArr2) {
        if (strArr == null || strArr2 == null || strArr.length != strArr2.length) {
            return false;
        }
        HashSet hashSet = new HashSet();
        for (String str : strArr) {
            hashSet.add(str);
        }
        HashSet hashSet2 = new HashSet();
        for (String str2 : strArr2) {
            hashSet2.add(str2);
        }
        return hashSet.equals(hashSet2);
    }

    public static void setCuidDataShable(Context context, boolean z) {
        File file = new File(context.getApplicationContext().getFilesDir(), SELF_CUID_FILE);
        Context applicationContext = context.getApplicationContext();
        if (file.exists() && (sCachedCuidInfo == null || sDataCuidInfoShable != z)) {
            tryToModifyChmodForSelfFile(applicationContext, z);
        }
        sDataCuidInfoShable = z;
    }

    /* access modifiers changed from: private */
    public static void setExternalDeviceId(String str, String str2) {
        File file;
        if (!TextUtils.isEmpty(str)) {
            File file2 = new File(Environment.getExternalStorageDirectory(), EXT_DIR);
            File file3 = new File(file2, EXT_FILE);
            try {
                if (file2.exists() && !file2.isDirectory()) {
                    Random random = new Random();
                    File parentFile = file2.getParentFile();
                    String name = file2.getName();
                    do {
                        file = new File(parentFile, name + random.nextInt() + ".tmp");
                    } while (file.exists());
                    file2.renameTo(file);
                    file.delete();
                }
                file2.mkdirs();
                FileWriter fileWriter = new FileWriter(file3, false);
                fileWriter.write(Base64.encode(AESUtil.encrypt(AES_KEY, AES_KEY, (str + "=" + str2).getBytes()), "utf-8"));
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException | Exception unused) {
            }
        }
    }

    /* access modifiers changed from: private */
    public static void setExternalV2DeviceId(String str) {
        File file;
        File file2 = new File(Environment.getExternalStorageDirectory(), EXT_DIR);
        File file3 = new File(file2, EXT_FILE_V2);
        try {
            if (file2.exists() && !file2.isDirectory()) {
                Random random = new Random();
                File parentFile = file2.getParentFile();
                String name = file2.getName();
                do {
                    file = new File(parentFile, name + random.nextInt() + ".tmp");
                } while (file.exists());
                file2.renameTo(file);
                file.delete();
            }
            file2.mkdirs();
            FileWriter fileWriter = new FileWriter(file3, false);
            fileWriter.write(str);
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException | Exception unused) {
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private boolean tryPutSystemSettingValue(String str, String str2) {
        try {
            return Settings.System.putString(this.mContext.getContentResolver(), str, str2);
        } catch (Exception e) {
            handleThrowable(e);
            return false;
        }
    }

    @SuppressLint({"NewApi"})
    private static boolean tryToModifyChmodForSelfFile(Context context, boolean z) {
        File file = new File(context.getApplicationContext().getFilesDir(), SELF_CUID_FILE);
        if (!file.exists()) {
            return false;
        }
        if (Build.VERSION.SDK_INT >= 21) {
            return TargetApiSupport.doChmodSafely(file.getAbsolutePath(), z ? 436 : 432);
        } else if (z) {
            try {
                return file.setReadable(true, false);
            } catch (Exception e) {
                handleThrowable(e);
                return false;
            }
        } else {
            return file.setReadable(false, false) && file.setReadable(true, true);
        }
    }

    private synchronized void writeJobThread(CUIDInfo cUIDInfo) {
        new Thread(getWriteRunnable(cUIDInfo)).start();
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    @SuppressLint({"NewApi"})
    private boolean writeToCuidFile(String str) {
        int i;
        File file;
        int i2 = (!sDataCuidInfoShable || Build.VERSION.SDK_INT >= 24) ? 0 : 1;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = this.mContext.openFileOutput(SELF_CUID_FILE, i2);
            fileOutputStream.write(str.getBytes());
            fileOutputStream.flush();
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e) {
                    handleThrowable(e);
                }
            }
            if (Build.VERSION.SDK_INT >= 21) {
                if (i2 == 0 && sDataCuidInfoShable) {
                    i = 436;
                    file = new File(this.mContext.getFilesDir(), SELF_CUID_FILE);
                } else if (!sDataCuidInfoShable) {
                    i = 432;
                    file = new File(this.mContext.getFilesDir(), SELF_CUID_FILE);
                }
                return TargetApiSupport.doChmodSafely(file.getAbsolutePath(), i);
            }
            return true;
        } catch (Exception e2) {
            handleThrowable(e2);
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e3) {
                    handleThrowable(e3);
                }
            }
            return false;
        } catch (Throwable th) {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e4) {
                    handleThrowable(e4);
                }
            }
            throw th;
        }
    }

    /* JADX WARNING: Removed duplicated region for block: B:20:0x0026  */
    /* JADX WARNING: Removed duplicated region for block: B:24:0x0030  */
    /* JADX WARNING: Removed duplicated region for block: B:26:0x0036 A[SYNTHETIC, Splitter:B:26:0x0036] */
    /* JADX WARNING: Removed duplicated region for block: B:33:? A[RETURN, SYNTHETIC] */
    /* JADX WARNING: Removed duplicated region for block: B:35:? A[RETURN, SYNTHETIC] */
    private static void writeToFile(File file, byte[] bArr) {
        Throwable th;
        IOException e;
        SecurityException e2;
        FileOutputStream fileOutputStream = null;
        try {
            FileOutputStream fileOutputStream2 = new FileOutputStream(file);
            try {
                fileOutputStream2.write(bArr);
                fileOutputStream2.flush();
                try {
                    fileOutputStream2.close();
                } catch (IOException e3) {
                    handleThrowable(e3);
                }
            } catch (IOException e4) {
                e = e4;
                fileOutputStream = fileOutputStream2;
                handleThrowable(e);
                if (fileOutputStream == null) {
                }
            } catch (SecurityException e5) {
                e2 = e5;
                fileOutputStream = fileOutputStream2;
                try {
                    handleThrowable(e2);
                    if (fileOutputStream == null) {
                    }
                } catch (Throwable th2) {
                    th = th2;
                    if (fileOutputStream != null) {
                    }
                    throw th;
                }
            } catch (Throwable th3) {
                th = th3;
                fileOutputStream = fileOutputStream2;
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e6) {
                        handleThrowable(e6);
                    }
                }
                throw th;
            }
        } catch (IOException e7) {
            e = e7;
            handleThrowable(e);
            if (fileOutputStream == null) {
                fileOutputStream.close();
            }
        } catch (SecurityException e8) {
            e2 = e8;
            handleThrowable(e2);
            if (fileOutputStream == null) {
                fileOutputStream.close();
            }
        }
    }
}