sutoL
sutoL

Reputation: 1767

why is a minus sign prepended to my biginteger?

package ewa;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.math.BigInteger;
/**
 *
 * @author Lotus
 */
public class md5Hash {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String test = "abc";

        MessageDigest md = MessageDigest.getInstance("MD5");
        try {
            md.update(test.getBytes("UTF-8"));
            byte[] result = md.digest();
            BigInteger bi = new BigInteger(result);
            String hex = bi.toString(16);
            System.out.println("Pringting result");
            System.out.println(hex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(md5Hash.class.getName()).log(Level.SEVERE, null, ex);
        }


    }
}

i am testing conversion of byte to hex and when done, the end result has a minus sign on the beginning of the string, why does this happen? i have read the docs and it says it will add a minus sign, however i do not understand it. And will the minus sign affect the hash result? because i am going to implement it to hash password stored on my database

Upvotes: 2

Views: 931

Answers (2)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

Because the BigInteger happens to be negative, meaning the most significant bit is 1. If you want a positive number, use the sign-magnitude constructor:

new BigInteger(1, result)

I'm not clear why you're implementing your own MD5 hash wrapper. Why can't you just store the hash as a BINARY or BLOB?

Upvotes: 8

Peter Lawrey
Peter Lawrey

Reputation: 533492

BigIntegers are signed. In the byte representation, if the top bit is set, this shows as a negative number. One way around this is might be to append a 0 to the start of the array.

Upvotes: 0

Related Questions