MessageDigest类的使用

116 篇文章 22 订阅

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

在前面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;
	}

}


 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

u010142437

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值