结论
commons-codec的DigestUtils.sha1Hex(bytes1)计算sha1值
使用的是传入的整个数组的数据,也就是数组中的空数据依然会用来算sha1值,使用过程正如果是把数据存入数组,再计算sha1值需要特殊注意要截去数组中的空数据
如果没有截取空数据,会出现本博客的标题的问题
实验过程
加入commons-codec依赖
// https://mvnrepository.com/artifact/commons-codec/commons-codec
compile group: 'commons-codec', name: 'commons-codec', version: '1.14'
上代码
package com.ldzm.helloworld.learn;
import org.apache.commons.codec.digest.DigestUtils;
public class DigestUtilsTest {
public static void main(String[] args) {
byte[] bytes1 = new byte[3];
bytes1[0] = 'a';
bytes1[1] = 'b';
bytes1[2] = 'c';
// byte1's sha1Hex: a9993e364706816aba3e25717850c26c9cd0d89d
System.out.println("byte1's sha1Hex: " + DigestUtils.sha1Hex(bytes1));
byte[] bytes2 = new byte[3];
bytes2[0] = 'a';
bytes2[1] = 'b';
bytes2[2] = 'c';
// byte2's sha1Hex: a9993e364706816aba3e25717850c26c9cd0d89d
// 和 byte1的sha1值相同,从而可以说明sha1值得计算使用的是数据中的字节,和名字无关
System.out.println("byte2's sha1Hex: " + DigestUtils.sha1Hex(bytes2));
byte[] bytes3 = new byte[4];
bytes3[0] = 'a';
bytes3[1] = 'b';
bytes3[2] = 'c';
// byte3's sha1Hex: 686483805ac47ca14e03514f7481a7973b401762
// 和 byte1的sha1值不同,说明虽然数中存入的字节相同,但是byte3多了一个空数
System.out.println("byte3's sha1Hex: " + DigestUtils.sha1Hex(bytes3));
byte[] bytes4 = new byte[5];
bytes4[0] = 'a';
bytes4[1] = 'b';
bytes4[2] = 'c';
// byte4's sha1Hex: 81d60d692c64fd547905fffdfb7ac16e25747b0c
// 和 byte3的sha1值不同,有两个空数据,和有一个空数据的sha1值也不同,说明空格的多少也会影响sha1值得计算
System.out.println("byte4's sha1Hex: " + DigestUtils.sha1Hex(bytes4));
}
}
通过debug打断点发现,数据没有赋值的部分存入的是0,0再ASCII中是NULL

本文探讨了使用commons-codec的DigestUtils.sha1Hex(bytes1)计算文件SHA1值时,为何结果可能与文件原SHA1值不一致。问题在于该方法会考虑整个数组,包括未赋值的0(ASCII中的NULL),在存储数据到数组时必须注意截取有效数据,否则可能导致错误的结果。通过实验过程和代码示例,揭示了问题的根源。

2万+

被折叠的 条评论
为什么被折叠?



