Some notes about SHA. It stands for Secure Hash Algorithm. It computes a fixed-length message digest (String) of an input message of any length. The five algorithms are denoted SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. SHA-224, SHA-256, SHA-384, and SHA-512 are classify under SHA-2.
Differences among them is the bit length of the digest they produce. SHA-512 produce a 64-char String.

From the diagram above, obtained from Wikipedia, till date no attacks have been found against SHA-2.
After searching on google, hoping to find an example of how to implement SHA-512 on Java .. there were none ... then we found something similar. Since Java 1.4.2, there is the Java Cryptographic Extension (JCE). It support for a wide range of standard algorithms including RSA, DSA, AES, Triple DES, SHA, PKCS#5, RC2, and RC4.
So now what we have to do is change
MessageDigest md = MessageDigest.getInstance("SHA-1");
to
MessageDigest md = MessageDigest.getInstance("SHA-512");
and increase the HASH length in the CACHE table to 64.
My full method() code below
public static String SHA(String text)
throws CaptchaException {
MessageDigest md = null;
try {
// Can be MD5 (128bit), SHA-1(160bit), SHA-256, SHA-384,SHA-512
md = MessageDigest.getInstance("SHA-512");
byte data[] = md.digest(text.getBytes("UTF-8"));
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++ < 0);
}
return buf.toString();
}
// might be thrown by MessageDigest.getInstance
catch (NoSuchAlgorithmException e) {
throw new CaptchaException(e.getMessage());
}
// might be thrown by text.getBytes
catch (UnsupportedEncodingException e) {
throw new CaptchaException(e.getMessage());
}
}
No comments:
Post a Comment