APK校验和-二进制代码保护

问题描述 投票:3回答:1

如何计算Android中APK文件的CheckSum?我想计算APK校验和并在每次我的应用程序中进行比较。执行以查看是否有人修改了二进制代码?如何计算校验和并实现此目标?

android security apk binaryfiles
1个回答
2
投票

[2020年更新-Google Play现在可以优化,重新打包和重新签名上载的.apks(并在.apk中添加安全性meta data),因此该篡改检查不太可能仍然有效。最好使用SafetyNet attestation API来验证设备并依次验证您的应用-只需确保您正在服务器上离线验证签名即可。

以下是一些代码来校验您的APK。我写了一篇文章article并向您的应用程序添加了篡改检测(具有讽刺意味的是,它不包含apk校验和)。

private static long getApkFileChecksum(Context context) {
        String apkPath = context.getPackageCodePath();
        Long chksum = null;
        try {
            // Open the file and build a CRC32 checksum.
            FileInputStream fis = new FileInputStream(new File(apkPath));
            CRC32 chk = new CRC32();
            CheckedInputStream cis = new CheckedInputStream(fis, chk);
            byte[] buff = new byte[80];
            while (cis.read(buff) >= 0) ;
            chksum = chk.getValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chksum;
    }

您也可以使用此功能将apk的sha-256 ...

public static String getApkFileDigest(Context context) {
        String apkPath = context.getPackageCodePath();
        try {
            byte[] hashed= getDigest(new FileInputStream(apkPath), "SHA-256");
            return Base64.encodeToString(hashed, Base64.DEFAULT);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    public static final int BUFFER_SIZE = 2048;

    public static byte[] getDigest(InputStream in, String algorithm) throws Throwable {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        try {
            DigestInputStream dis = new DigestInputStream(in, md);
            byte[] buffer = new byte[BUFFER_SIZE];
            while (dis.read(buffer) != -1) {
            }
            dis.close();
        } finally {
            in.close();
        }
        return md.digest();
    }
© www.soinside.com 2019 - 2024. All rights reserved.