【问题标题】:How to calculate hash of APK file programmatically?如何以编程方式计算 APK 文件的哈希值?
【发布时间】:2019-05-20 15:53:34
【问题描述】:

我想从应用内部计算 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) {
        }
    }
}

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

这里有什么问题?

【问题讨论】:

  • 再次检查您是否真的在针对修改后的版本运行。我建议完全卸载,然后在代码更改后重新安装。
  • 你是对的!单击“调试应用程序”是不够的,我不得不重建项目以获得不同的哈希值。你想写答案还是我应该写?

标签: android apk android-package-managers


【解决方案1】:

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

【讨论】:

  • 重建项目以获得新的哈希值就足够了,无需卸载。之后只点击“调试应用程序”显然足以获得新的哈希值,但重建似乎是安全的。
猜你喜欢
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2021-07-29
  • 2022-01-04
相关资源
最近更新 更多