I'm generating a SHA256 hash of few files and some of them return 63 characters instead of 64. How can it be possible?

你离开我真会死。 提交于 2019-12-05 07:51:04

问题


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

回答1:


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

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.

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

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

or

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


来源:https://stackoverflow.com/questions/18699268/im-generating-a-sha256-hash-of-few-files-and-some-of-them-return-63-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!