Pure Java implementation of MD5 Algorithm
The following Java algorithm generates MD5 hashes from String, Byte array and File.
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * @author Nikos Siatras */ public class MD5 { public MD5() { } /** * Return the MD5 string representation of the given string * * @param str is the string to get the MD5 * @return * @throws NoSuchAlgorithmException */ public String getMD5FromString(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] array = md.digest(str.getBytes()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString().toUpperCase(); } /** * Return the MD5 string representation of the given byte array * * @param bytes is the byte array to get the MD5 * @return * @throws NoSuchAlgorithmException */ public String getMD5FromByteArray(byte[] bytes) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] array = md.digest(bytes); StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString().toUpperCase(); } /** * Return the MD5 string representation of the given file * * @param file is the file to get the MD5 * @return * @throws NoSuchAlgorithmException * @throws IOException */ public String getMD5FromFile(File file) throws NoSuchAlgorithmException, IOException { MessageDigest md = MessageDigest.getInstance("MD5"); // SHA or MD5 String hash = ""; byte[] data = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(data); fis.close(); // Reads it all at one go. Might be better to chunk it. md.update(data); byte[] digest = md.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(digest[i]); if (hex.length() == 1) { hex = "0" + hex; } hex = hex.substring(hex.length() - 2); hash += hex; } return hash.toUpperCase(); } }
0 comments:
Post a Comment