Produce a Hash String of Fixed Length

Viewed 6747

I would like to produce a hashed string of fixed length. I am using the MessageDigest API for this. I noticed this function in the API but it returns an integer not a byte array.

When I tried to use this overloaded digest method, I get either a java.security.DigestException: Length must be at least 32 for SHA-256 digests or Output buffer too small for specified offset and length.

Can somebody give an example of how to produce a hash value of fixed length please?

2 Answers

You could use Commons Codec DigestUtils to generate hex representation of a hash. There are a few algorithms available:

e.g.

String input = "Hello World";
String sha1 = DigestUtils.sha1Hex(input);
System.out.println(sha1); // 0a4d55a8d778e5022fab701977c5d840bbc486d0

It can be achieved like this:

import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class TestA {

    public static void main(String [] args) throws Exception {
        String input = "Hello World";
        System.out.println(DatatypeConverter.printHexBinary(hashBytes(input.getBytes(StandardCharsets.UTF_8))));
    }

    public static byte[] hashBytes(byte [] bytes) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(bytes);
        return md.digest();
    }
}

SHA-256 can of course be used instead of SHA-1

Related