Search code examples
javahashsha1message-digest

Is there's a hexToString implemented method in Java for Hashing?


I'm working in a little method that hashes a String. Looking for information, I could find that MessageDigest can help me to make this task, here

Compute SHA-1 of byte array

But now I have a question. It seems that the procedure to hash a String in Java it's always the same:

  1. You create your MessageDigester and specify the algorithm to use.
  2. You updates the MessageDigester with the String to hash
  3. Then you call MessageDigester.digest and you get a byte[].

If one of the most used fonctionnalities of a hash it's to get the String version of this hash, why (in the question I refered and some other) people have to implement their convToHex method?

private static String convToHex(byte[] data) {
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < data.length; i++) {
                int halfbyte = (data[i] >>> 4) & 0x0F;
                int two_halfs = 0;
                do {
                    if ((0 <= halfbyte) && (halfbyte <= 9))
                        buf.append((char) ('0' + halfbyte));
                    else
                            buf.append((char) ('a' + (halfbyte - 10)));
                    halfbyte = data[i] & 0x0F;
                } while(two_halfs++ < 1);
            }
            return buf.toString();
        }

Is there a Java method that allows me to make this parse between the byte[] returned by the MessageDigester and a String?? If it exists, where is it?? If not, why do I have to make my own method?

Thanks.


Solution

  • You could use Commons Codec which has a Hex class. Apart from that you can write the conversion much shorter if you don't want to include another dependency:

    private final static String HEX_CHARS = "0123456789ABCDEF";
    
    @Override
    public String toString() {
        String res = "";
        for(byte b : data) {
            res += HEX_CHARS.charAt((b >> 4) & 0xF);
            res += HEX_CHARS.charAt(b & 0xF);
        }
        return res;
    }
    

    (I know, I know, string concatenation in a loop, the byte arrays I have are of a fixed short length. Feel free to change it to use StringBuilder.)