Question

I am trying to generate sha1 of a string by referring to the example in this link - http://www.sha1-online.com/sha1-java/

public class HashTextTest {

/**
 * @param args
 * @throws NoSuchAlgorithmException 
 */
public static void main(String[] args) throws NoSuchAlgorithmException {
    System.out.println(sha1("test string to sha1"));
}

static String sha1(String input) throws NoSuchAlgorithmException {
    MessageDigest mDigest = MessageDigest.getInstance("SHA1");
    byte[] result = mDigest.digest(input.getBytes());
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < result.length; i++) {
        sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
    }

    return sb.toString(); 

   }
}

I dont want to have this messy line of code from string buffer - sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));.

Is there any alternate way to doing this?

Was it helpful?

Solution

What you need here is to format a byte as two hex digits.

sb.append(String.format("%02x", result[i])); would do it.

If you need uppercase hex digits, use

sb.append(String.format("%02X", result[i]));


Additionaly if you do not mind spaces between encoded bytes, you can use

new sun.misc.HexDumpEncoder().encode(result).substring(6);

to encode the whole byte[] at once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top