3

Hello I am using below code to encrypt a string. I found MD5 make working in -127 - +128 values.

I am getting value in minus for.

public static void main(String[] args) throws Exception {
        String message = "smile";

        encrypt("Jack the Bear");
    }

    public static void encrypt(String password) throws Exception {

      byte byteData[] =null;

     MessageDigest md = null;
       try {
         md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes("US-ASCII"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

      byteData = md.digest();
      System.out.println(Arrays.toString(byteData));


    }

My Output : [101, 23, 66, 106, 91, -51, 6, 119, -13, 23, -101, 108, -122, 27, 20, -124]

Real output : [101, 23, 66, 106, 91, 205, 6, 119, 243, 23, 155, 108, 134, 27, 20, 132]

NovusMobile
  • 1,813
  • 2
  • 21
  • 48

2 Answers2

4

This is because the byte type in Java (like almost all other types) is signed, which means it has a range of -128..127.

If you want to convert this range to an unsigned range (0..255), do this:

byte b = -2;
int i = b & 0xff;

Print your result byteData like this:

for (byte b : byteData)
    System.out.print((b & 0xff) + " ");

If you want to print the result in hexadecimal format:

for (byte b : byteData)
    System.out.printf("%02x ", b);
icza
  • 389,944
  • 63
  • 907
  • 827
2

Your digest is computed correctly, there's nothing wrong with negative byte values.

Byte type in Java has range from -128 to +127 which might be somewhat surprising - many people assume that byte is unsigned, but Java doesn't have unsigned number types.

qbd
  • 533
  • 1
  • 6
  • 18
  • 1
    Almost. Java's only unsigned type is `char` (I know, it doesn't really matter since you won't be doing any calculations with char). – Kayaman May 11 '15 at 07:17
  • @Kayman Well, I don't consider char to be number type (box type Character doesn't implement java.lang.Number after all), even though it has ordinal value. – qbd May 11 '15 at 07:20
  • True, you did specify "unsigned **number** types". Well, semantics semantics. – Kayaman May 11 '15 at 07:26