Pergunta

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();

Foi útil?

Solução

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 :)

Outras dicas

You need to specify which SHA-2 variant you'd like to use: SHA-256 or SHA-512. Use those as the digest names.

If you haven't already I'd recommend reading the SUN docs on JCA, particularly the MessageDigest. If you look at the default SUN providers, you'll notice that SHA-2 doesn't actually exist, perhaps try 'SHA-512' instead.

Try:

String message = "Some Message";

MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");

messageDigest.update(message.getBytes("UTF-16BE"));
byte[] digest = messageDigest.digest();

StringBuffer digestInHex = new StringBuffer();

for (int i = 0, l = digest.length; i < l; i++) {
    // Preserve the bit representation when casting to integer.
    int intRep = digest[i] & 0xFF;
    // Add leading zero if value is less than 0x10.
    if (intRep < 0x10)  digestInHex.append('\u0030');
    // Convert value to hex.
    digestInHex.append(Integer.toHexString(intRep));
}

System.out.println(digestInHex.toString());

What error? "sha1hash cannot be resolved"? You missed to declare the variable. Pressing ctrl-1 in eclipse does the job. What about sha2hash? I'd say, there should be only one such variable. What about text and textstring? Another self-confusion?

Btw., there's no such thing as "the SHA-2". It's a family of functions, containing e.g., SHA-256. So try something like this:

public static byte[] sha2(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    final MessageDigest mesd = MessageDigest.getInstance("SHA-256");
    mesd.update(text.getBytes("iso-8859-1"), 0, text.length());
    return mesd.digest();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top