tags:

views:

133

answers:

2

I need to create the hash of a the html of a webpage (from its URL) using SHA1 or MD5 in java, but I don't know how to do it... can you help me?

+1  A: 

DigestUtils.sha(String) should do the job for the URI or the HTML of the web page, though it's on you to get the HTML of the page from its URI if that's part of the problem. If so, you may want to look into using Commons HttpClient to GET the page.

Hank Gay
Yep, it will, but is not the java standard library. I don't want to use library that aren't necessary.
Raffo
If that's a constraint, it should be in the question. Also, define necessary, because reimplementing something that is already provided in a well-tested library seems like the height of unnecessity.
Hank Gay
It is not a constraint I can use external libraries, but I'm not sure I can't do this using the standard library and just a bit of coding. Of course you're right that is better to use a well tested library, but I don't know if the java api offers something similar..
Raffo
+1  A: 

Raffaele Di Fazio:

you can use this function to generate MD5 as HashValue from the String; for example,

   String hashValue = MD5Hash("URL or HTML".getBytes());


  /**
     * MD5 implementation as Hash value 
     * 
     * @param a_sDataBytes - a original data as byte[] from String
     * @return String as Hex value 
     * @throws NoSuchAlgorithmException 
     */

    public static String MD5Hash(byte[] dataBytes) throws NoSuchAlgorithmException {
     if( dataBytes == null) return "";

     MessageDigest md = MessageDigest.getInstance("MD5");
     md.update(dataBytes);
     byte[] digest = md.digest();

     // convert it to the hexadecimal 
     BigInteger bi = new BigInteger(digest);
     String s = bi.toString(16);
     if( s.length() %2 != 0)
     {
      s = "0"+s;
     }
     return s;
    }

I hope it helps. Please, let us know if it is right direction for that question.

Tiger.

Tiger
Thanks, this is what I was looking for. I'm going to test this function and try to adapt it to my code.
Raffo