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

时间:2014-08-01 06:59:06

标签: android security apk binaryfiles

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

1 个答案:

答案 0 :(得分:1)

这里有一些代码来校验你的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();
    }