Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHA hash function gives a negative output

Tags:

java

hash

sha

dsa

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.

like image 760
Egor Avatar asked Jun 15 '11 11:06

Egor


1 Answers

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;
like image 146
Martijn Courteaux Avatar answered Sep 27 '22 20:09

Martijn Courteaux