我需要哈希函数始终返回 64 char hex,但有时,根据文件,它返回 63,这对我来说是个问题。由于业务原因,我总是需要 64 个字符。这完全随机发生在任何类型和大小的文件中。有谁知道为什么会这样?按照我的代码:
public static String geraHash(File f) throws NoSuchAlgorithmException, FileNotFoundException
{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
InputStream is = new FileInputStream(f);
byte[] buffer = new byte[8192];
int read = 0;
String output = null;
try
{
while( (read = is.read(buffer)) > 0)
{
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1,md5sum);
output = bigInt.toString(16);
}
catch(IOException e)
{
throw new RuntimeException("Não foi possivel processar o arquivo.", e);
}
finally
{
try
{
is.close();
}
catch(IOException e)
{
throw new RuntimeException("Não foi possivel fechar o arquivo", e);
}
}
return output;
}