欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android校验应用签名是否被篡改

程序员文章站 2022-07-10 08:23:01
...

Android校验应用签名是否被篡改

1.获取应用签名并校验MD5或者SHA1

/**
     * 检测签名
     */
    private boolean checkSignature() {
        Context context = WXApplication.getInstance();
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            Signature[] signatures = packageInfo.signatures;

            if (signatures != null) {
                for (Signature signature : packageInfo.signatures) {
                    //获取MD5或者SHA1
                    MessageDigest md = MessageDigest.getInstance("MD5");
                    md.update(signature.toByteArray());

                    String currentSignature = bytesToHexString(md.digest()).toUpperCase();

                    if ("YOUR SIGENATURE".equals(currentSignature)) {
                        return true;
                    }
                }
            } else {
                LogUtil.i("signatures ==null");
            }

        } catch (NameNotFoundException e) {
            e.printStackTrace();
            LogUtil.e(e);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            LogUtil.e(e);
        }

        return false;
    }

/**
 * byte转16进制String
 *
 * @param src 数据源
 * @return string
 */
public String bytesToHexString(byte[] src) {
    StringBuilder stringBuilder = new StringBuilder();
    if (src == null || src.length <= 0) {
        return "";
    }

    for (byte by : src) {
        int v = by & 0xFF;
        String hv = Integer.toHexString(v);
        if (hv.length() < 2) {
            stringBuilder.append(0);
        }
        stringBuilder.append(hv);
    }
    return stringBuilder.toString();
}