Here you can find the source of md5(final byte[] data)
Parameter | Description |
---|---|
data | A byte array |
public static final String md5(final byte[] data)
//package com.java2s; //License from project: Apache License import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { /**// www . j a va 2 s . c o m * Returns the MD5 of the specified bytes * * @param data * A byte array * @return the MD5 sum */ public static final String md5(final byte[] data) { if (null == data || data.length <= 0) { throw new IllegalArgumentException("empty data"); } try { final MessageDigest md = MessageDigest.getInstance("MD5"); return toHexString(md.digest(data)); } catch (final NoSuchAlgorithmException e) { return null; } } /** * Returns the MD5 of the specified string * * @param data * A string value * @return the MD5 sum */ public static final String md5(final String data) { if (null == data) { throw new IllegalArgumentException("null string"); } try { final MessageDigest md = MessageDigest.getInstance("MD5"); return toHexString(md.digest(data.getBytes())); } catch (final NoSuchAlgorithmException e) { return null; } } /** * Returns the MD5 of the specified file * * @param file * A file * @return the MD5 sum of the file * @throws FileNotFoundException * @throws IOException */ public static String md5(final File file) throws IOException { if (null == file || !file.exists()) { throw new IllegalArgumentException("file is unavailable"); } final byte[] buf = new byte[1024 * 8]; try { final MessageDigest md = MessageDigest.getInstance("MD5"); InputStream is = null; try { is = new FileInputStream(file); for (int n = 0; (n = is.read(buf)) != -1;) { md.update(buf, 0, n); } } finally { if (is != null) { try { is.close(); } catch (IOException e) { } is = null; } } return new BigInteger(1, md.digest()).toString(16); } catch (final NoSuchAlgorithmException e) { return null; } } /** * Returns the specified data as hex sequence * * @param data * The data * @return a hex string */ public static String toHexString(byte[] data) { final int n = data.length; final StringBuilder hex = new StringBuilder(); for (int i = 0; i < n; i++) { final byte b = data[i]; hex.append(String.format("%02x", b & 0xff)); } return hex.toString(); } }