MessageDigest类的使用

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)、博主微信(guyun297890152)、QQ技术交流群(183198395)。

在前面java中的MessageDigest类中简要介绍了它的一些作用和方法,下面给个例子,对文件和字符串MD5分别给了两个例子,代码如下:

package com.home;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Test {
	public static void main(String[] args) {
		String str1 = "I love Java";
		System.out.println(getMD5Str(str1));
		try {
			System.out.println(getFileMD5String("C:/Main.java"));
			System.out.println(getFileMD5("C:/Main.java"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 对字符串进行MD5加密
	 * 
	 * @param input
	 * @return
	 */
	public static String getMD5Str(String input) {
		try {
			MessageDigest m = MessageDigest.getInstance("MD5");
			m.update(input.getBytes());
			byte[] md5Data = m.digest();
			return byteArrayToHex(md5Data);
			// return byteArrayToHex2(md5Data);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 将字节数组换成成16进制的字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	public static String byteArrayToHex2(byte[] byteArray) {
		String output = new String();
		for (int i = 0; i < byteArray.length; i++) {
			int b = (0xFF & byteArray[i]);
			if (b <= 0xF) {
				output += "0";
			}
			output += Integer.toHexString(b);
		}
		output = output.toUpperCase();
		return output;
	}

	/**
	 * 将字节数组换成成16进制的字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	private static String byteArrayToHex(byte[] byteArray) {
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		char[] resultCharArray = new char[byteArray.length * 2];
		int index = 0;
		for (byte b : byteArray) {
			resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArray[index++] = hexDigits[b & 0xf];
		}
		return new String(resultCharArray);
	}

	/**
	 * 对文件进行MD5加密
	 * 
	 * @param inputFile
	 * @return
	 * @throws IOException
	 */
	public static String getFileMD5(String inputFile) throws IOException {
		int bufferSize = 256 * 1024;
		FileInputStream fileInputStream = null;
		DigestInputStream digestInputStream = null;
		try {
			// 拿到一个MD5转换器(同样,这里可以换成SHA1)
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			// 使用DigestInputStream
			fileInputStream = new FileInputStream(inputFile);
			digestInputStream = new DigestInputStream(fileInputStream,
					messageDigest);
			// read的过程中进行MD5处理,直到读完文件
			byte[] buffer = new byte[bufferSize];
			while (digestInputStream.read(buffer) > 0)
				;
			// 获取最终的MessageDigest
			messageDigest = digestInputStream.getMessageDigest();
			// 拿到结果,也是字节数组,包含16个元素
			byte[] resultByteArray = messageDigest.digest();
			// 同样,把字节数组转换成字符串
			return byteArrayToHex(resultByteArray);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (digestInputStream != null) {
					digestInputStream.close();
				}
				if (fileInputStream != null) {
					fileInputStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 得到文件MD5
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public static String getFileMD5String(String path) throws IOException {
		File file = new File(path);
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			FileInputStream in = new FileInputStream(file);
			FileChannel ch = in.getChannel();
			MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY,
					0, file.length());
			messageDigest.update(byteBuffer);
			return byteArrayToHex(messageDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

}


 

你可能感兴趣的:(JAVA,Java之旅,java,MD5,MessageDigest)