似乎无法弄清楚我在这里出错的地方:
private static String generateHashFromFile(String filePath) {
try {
final int BUFSZ = 32768;
MessageDigest sha = MessageDigest.getInstance("SHA-256");
FileInputStream in = new FileInputStream(filePath);
BufferedInputStream is = new BufferedInputStream(in, BUFSZ);
byte[] buffer = new byte[BUFSZ];
int num = -1;
while((num = is.read(buffer)) != -1) {
sha.update(buffer, 0, num);
}
is.close();
byte[] hash = sha.digest();
return byteArrayToHex(hash);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static String byteArrayToHex(byte[] barray)
{
char[] c = new char[barray.length * 2];
byte b;
for (int i = 0; i < barray.length; ++i)
{
b = ((byte)(barray[i] >> 4));
c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(barray[i] & 0xF));
c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
return new String(c);
}
我得到如下字符串:
")469.76F5941+31E25)6,9,C26)978)4*917180A4C(B7C,E,D+6,7133C705167"
显然不是十六进制!
问题:
- 哈希生成代码是否正确?
- 十六进制编码方法是否正确?
- 我在编码方面遗漏了什么吗?