Use of the Big Integer class to build an MD5 hash

Asked

Viewed 78 times

0

I found in another post right here in the OS the following example of code to generate a hash through MD5:

String message = "teste1234";
byte[] hash = MessageDigest.getInstance("MD5").digest(message.getBytes("UTF-8"));
System.out.println("MD5: " + new BigInteger(1, hash).toString(16));

However, I did not understand how it is possible to convert a number (represented by Biginteger) into a text.

  • See the response of utluiz♦, in it, it explains exactly everything that is happening in this conversion.

  • In fact, the vast majority of java classes have the method toString(), it is he who makes this conversion. Each class has its own implementation of this method.

  • @Diegof has some he doesn’t have?

  • @bigown so I replied as a comment, not sure if all has kkkk

1 answer

1

In fact the toString(16) method will convert to hexadecimal so of 16. as you can see hash is a byte array and if you are to observe the Biginteger constructor the byte[] parameter is represented as: Binary representation of the magnitude of the number. You do not necessarily need to use the Biginteger class for such a task. A practical example for you to better understand the logic:

    String message = "teste1234";
    byte[] hash = MessageDigest.getInstance("MD5").digest(message.getBytes("UTF-8"));

    char[] HEX_CHARS = "0123456789abcdef".toCharArray();
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < hash.length; ++i)
    {
    //Operadores bitwise para representar o valor do byte em hexadecimal
    chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
    chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    System.out.println("MD5: " + new String(chars));

In case the value is converted to "String" this is nothing more than the bitwise operators as shown above.

Hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.