Search code examples
javadata-integritysha2

how to verify data integrity using SHA2?


package abc.xyz;
import java.io.UnsupportedEncodingException; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 

public class SHA2{ 

    private static String convertToHex(byte[] data) { 
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) { 
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do { 
                if ((0 <= halfbyte) && (halfbyte <= 9)) 
                    buf.append((char) ('0' + halfbyte));
                else 
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        } 
        return buf.toString();
    }      
public static String SHA2(String text) 
            throws NoSuchAlgorithmException, UnsupportedEncodingException  { 

        MessageDigest mesd;
        mesd = MessageDigest.getInstance("SHA-2");
        byte[] sha2hash = new byte[40];
        mesd.update(text.getBytes("iso-8859-1"), 0, text.length());
        sha2hash = mesd.digest();//error
        return convertToHex(sha2hash);
    } }

I am getting error in implementing digest();


Solution

  • SHA-2 isn't an algorithm itself. Wikipedia:

    SHA-2 is a set of cryptographic hash functions (SHA-224, SHA-256, SHA-384, SHA-512)

    I think all but SHA-224 should be available.

    public static String SHA2(String text) 
        throws NoSuchAlgorithmException, UnsupportedEncodingException  { 
    
      MessageDigest mesd = MessageDigest.getInstance("SHA-256");
      byte[] bytes = text.getBytes("iso-8859-1");
      mesd.update(bytes, 0, bytes.length);
      byte[] sha2hash = mesd.digest();
      return convertToHex(sha2hash);
    } 
    

    Additionally, the byte array you create isn't necessary. The digest() method returns an array itself. The assignment operator never writes a result into an existing array. Unless you specify an index of course.

    One more thing. I wouldn't use text.length() when calling update(..) as it's not necessarily the same as the length of the resulting byte array. This is mainly the case for multibyte character encoding like UTF-8. It might also occur for characters that can't be mapped, depending on your strategy of choice. Well, the main point is though: you don't need to know what I'm talking about. Simply use an array's .length instead to be save :)