本文介绍了我正在生成几个文件的 SHA256 哈希值,其中一些文件返回 63 个字符而不是 64 个字符.这怎么可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要哈希函数总是返回 64 个十六进制字符,但有时,根据文件,它返回 63,这对我来说是个问题.由于业务原因,我总是需要 64 个字符.这对于任何类型和大小的文件都是完全随机的.有谁知道为什么会这样?按照我的代码:

I need the hash function always to return 64 char hex but sometimes, depending on a file, it returns 63 and that's a problem for me. Due to business reasons I need always 64 chars. And that happens completely random with Any kind and size of file. Does anyone know why it happens? Follow my code:

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;
}

推荐答案

其实就是32字节.第一个字节的前半部分为零.(第一个字节看起来像:0000 xxxx)

In fact, there is 32 byte. Just first half of first byte is zero. (first byte looks like: 0000 xxxx)

因此,当您将其转换为字符串时,它有 63 个十六进制值,即 31.5 个字节,因此它是 32 个字节.这(32 字节)正是它应该的样子.

So, when you are converting it to string, it has 63 hex value which is 31.5 bytes, so it is 32 bytes in bytes. This (32 byte) is exactly what it should to be.

当字符串长度为 63 时,您可以只写 0 字符串的开头.

You can just write 0 start of string when its length is 63.

if (output.length == 63){
    output = "0" + output;
}

while (output.length < 64){
    output = "0" + output;
}

这篇关于我正在生成几个文件的 SHA256 哈希值,其中一些文件返回 63 个字符而不是 64 个字符.这怎么可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 13:03