Java has a built-in MessageDigest class which makes it easy to implement an MD5 or SHA-1 hash (among others). Both of these algorithms produce one-way hashes (they cannot be changed back to their original form), and they are usually used for encryption and for checking the integrity of files (checksum). Although they are probably deemed partially insecure, they are still very widely used.
The following class is a “digester” that I frequently use if I need to implement some encryption (for storing passwords, for example). To use it, simply include it in your project, and call it like:
String password = "test"; String md5Password = Digester.md5( password ); String sha1Password = Digester.sha1( password );
Digester
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Digester {
/**
* This method is used for SHA-1
* message digest.
*
* @param byte[] data
* @return SHA-1 Encrypted String
*/
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);
} // end for loop
return buf.toString();
} // end method convertToHex
/**
* Returns an MD5 hash of the given
* string.
*
* @param String password
* @return MD5 Encrypted String
*/
public static String md5( String password ) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update( password.getBytes(), 0, password.length() );
return new BigInteger(1,md.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} // end try
return "Error";
} // end method md5
/**
* This method returns a SHA-1
* encrypted String.
*
* @param String text
* @return SHA-1 Encrypted String
*/
public static String sha1( String password ) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] sha1hash = new byte[40];
md.update(password.getBytes("iso-8859-1"), 0, password.length());
sha1hash = md.digest();
return convertToHex(sha1hash);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} // end try
return "Error";
} // end method sha1
} // end class Digester
Tags: checksum, cryptography, encryption, md5, sha-1
