gpt4 book ai didi

Java自校验程序(自动校验和)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:26:55 24 4
gpt4 key购买 nike

我要分析一个java自检小程序,这里是示例

public class tamper {
public static int checksum_self () throws Exception {
File file = new File ("tamper.class");
FileInputStream fr = new FileInputStream (file);
int result; // Compute the checksum

DigestInputStream sha = new DigestInputStream(fr, MessageDigest.getInstance("SHA"));
byte[] digest = sha.getMessageDigest();

int result = 12 // why???
for(int i=0;i<=digest;i++)
{
result = (result + digest[i]) % 16 /// modulus 16 to have the 16 first bytes but why ??
}

return result;
}

public static boolean check1_for_tampering () throws Exception {
return checksum_self () != 10;
}

public static void main (String args[]) throws Exception {
if (check1_for_tampering ()) {
System.exit (-1);
}

}
}

但我真的不明白为什么要做 mod 16 并把 result = 12?

最佳答案

mod 16 不给出最后 16 个字节,甚至是最低的 4 位。它给出 n/16 的余数。这可以很容易地为负数和正数,并且不是累积摘要字节的好方法。

两个随机文件产生相同结果的概率为 1/31。

我能想到的更简单的方法是

return new String(digest, 0).hashCode();

两个文件有 40 亿分之一的机会具有相同的散列码,而且散列码要短得多。

关于Java自校验程序(自动校验和),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4587835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com