Search code examples
javahashshadsa

SHA hash function gives a negative output


I'm trying to implement DSA signature algorithm and I'm stuck on a problem. I'm using the java.security MessageDigest class, here's the code:

MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
md.update(text.getBytes());
return new BigInteger(md.digest());

Text is a random String object. Problem is that this code gives me negative values of hash, which is not accepted by the algorithm. Am I doing something wrong? Thanks in advance.

P.S. By the way, I've also tried to implement DSA without using BigIntegers, is this possible? I've not found the L and N values lesser than 1024 and 160, so I have no idea what values should I take and what hash-function should I use. Will be very thankful to hear the answers on these questions.


Solution

  • MessageDigest md;
    md = MessageDigest.getInstance("SHA-1");
    md.update(text.getBytes());
    return new BigInteger(1, md.digest()); // use this 1 to tell it is positive.
    

    Then you can convert your hash to a String using:

    String hash = biginteger.toString(16);
    

    Then optionally prepend the leading zeros.

    String zeros = String.format("%032d", 0);
    hash = zeros.substring(hash.length()) + hash;