Thursday, September 23, 2010

Password Encryption ‘n’ Decryption.




What is MD5?

The MD5 hash also known as checksum for a file is a 128-bit value, something like a fingerprint of the file. There is a very small possibility of getting two identical hashes of two different files. This feature can be useful both for comparing the files and their integrity control. MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function. It has been employed in a wide variety of security applications. An MD5 hash is typically expressed as a 32-digit hexadecimal number.

Encryption is used for converting a given String value to its equivalent hexadecimal code. Decryption is nothing but just the vice versa.

MD5.java:





public class MD5 {

public static String digest(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}

private static String convertToHex(byte[] b) {
StringBuilder result = new StringBuilder(32);
for (int i = 0; i < b.length; i++) {
result.append(Integer.toString((b[i] & 0xff) + 0x100, 16)
.substring(1));
}
System.out.println(result.toString());
return result.toString();
}

}




Explanation:


The first getInstance() method accepts an argument, which is suppose to be the algorithm to be used i.e MD5 ,SHA ,SHA1 etc. If no provider can be found that implements the given algorithm, a NoSuchAlgorithmException is thrown. If the named provider cannot be found, a NoSuchProviderException is thrown.


Then comes the update() method which accepts three arguments i.e (byte[] input, int offset, int length) and suppose to be the subset of the array of data. This method may be called any number of times to add the desired data to the digest.


After the data is accumulated we have to compute the data using digest() method. The resulting digest is returned as a byte array. Once a digest has been calculated, the internal state of the algorithm is reset.


The resulting byte array is then transformed to corresponding hexadecimal equivalent in the convertToHex() method. Now the encrypted format of the string is ready to be used in your project.


No comments:

Post a Comment