如何以编程方式计算APK文件的哈希值?

曼努埃尔

我想从应用程序内部计算 APK 文件的 MD5 哈希值。

PackageInfo info = App.getInstance().getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
File file = new File(info.applicationInfo.sourceDir);
String hash = MD5.calculateMD5(file);

MD5 哈希计算如下:

private String calculateMD5() {

    MessageDigest digest;

    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        return null;
    }

    InputStream is;
    try {
        is = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        return null;
    }

    byte[] buffer = new byte[8192];
    int read;
    try {
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] md5sum = digest.digest();
        BigInteger bigInt = new BigInteger(1, md5sum);
        String output = bigInt.toString(16);
        output = String.format("%32s", output).replace(' ', '0');
        return output;
    } catch (IOException e) {
        throw new RuntimeException("Unable to process file for MD5", e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
        }
    }
}

但是,在模拟器中运行时,即使我更改了源代码,我也会不断获得相同的哈希值。

这里有什么问题?

代码学徒

仔细检查您是否真正针对修改后的构建运行。我建议在代码更改后完全卸载然后重新安装。在调试 Web 应用程序两个小时后发现我没有部署我所做的更改后,我艰难地学到了这一点。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章