Java获取文件的hash值(SHA256)

目录

简介

获取网络文件的sha256值(方式一)

获取本地文件的sha256值(方式二)


简介

        在工作开发当中需求要通过文件的hash值比对文件是否被篡改过,于是通过使用了(sha256)hash值进行比对,因为对于任意长度的消息,SHA256都会产生一个256bit长的哈希值,通常用一个长度为64的十六进制字符串来表示。

获取网络文件的sha256值(方式一)

        首先通过InputStream获取网络URL文件,然后创建临时文件,再通过FileInputStream以字节流的方式逐块读取文件内容,然后通过DigestInputStream将读取的数据传递给MessageDigest来计算SHA256哈希值。这样可以避免将整个文件加载到内存中,而是通过缓冲区逐块处理文件内容。

JAVA代码如下:(文件地址自己改一下)

/**
	 * 计算SHA256哈希值
	 * @param filePath 文件路径
	 * @return 字节数组
	 * @throws IOException IO异常
	 * @throws NoSuchAlgorithmException NoSearch算法异常
	 */
	public static byte[] calculateSHA256(String filePath) throws IOException, NoSuchAlgorithmException {
		MessageDigest digest = MessageDigest.getInstance("SHA-256");

		//获取网络URL文件
		InputStream fis2 = new URL(filePath).openStream();
		//创建临时文件
		File file = File.createTempFile(IdWorker.getIdStr(),"");
		FileUtil.writeFromStream(fis2,file);

		try (
				FileInputStream fis = new FileInputStream(file);
				FileChannel channel = fis.getChannel();
				DigestInputStream dis = new DigestInputStream(fis, digest)) {
				ByteBuffer buffer = ByteBuffer.allocate(8192); // 8 KB buffer
			while (channel.read(buffer) != -1) {
				buffer.flip();
				digest.update(buffer);
				buffer.clear();
			}
			return digest.digest();
		}
	}

	/**
	 * 将字节数组转换为String类型哈希值
	 * @param bytes 字节数组
	 * @return 哈希值
	 */
	private static String bytesToHex(byte[] bytes) {
		StringBuilder result = new StringBuilder();
		for (byte b : bytes) {
			result.append(String.format("%02x", b));
		}
		return result.toString();
	}

	public static void main(String[] args) {
		String filePath = "https://xxxxx/20230410/bfd71f584d9645b0a5e3d7a465119f0c.pdf";
		try {
			byte[] sha256 = calculateSHA256(filePath);
			String sha256Hex = bytesToHex(sha256);
			System.out.println("SHA256: " + sha256Hex);
		} catch (IOException | NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

响应结果:(这里的结果是我自己再测试的时候生成的)

SHA256: cffebd06c485d17b8a93308e1e39cc4c1636444b762c9c153ba8b29022392b98

获取本地文件的sha256值(方式二)

        通过FileInputStream以字节流的方式逐块读取文件内容,然后通过DigestInputStream将读取的数据传递给MessageDigest来计算SHA256哈希值。这样可以避免将整个文件加载到内存中,而是通过缓冲区逐块处理文件内容。

JAVA代码如下:(文件地址自己改一下)

/**
	 * 计算SHA256哈希值
	 * @param filePath 文件路径
	 * @return 字节数组
	 * @throws IOException IO异常
	 * @throws NoSuchAlgorithmException NoSearch算法异常
	 */
	public static byte[] calculateSHA256(String filePath) throws IOException, NoSuchAlgorithmException {
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		try (
				FileInputStream fis = new FileInputStream(filePath);
				FileChannel channel = fis.getChannel();
				DigestInputStream dis = new DigestInputStream(fis, digest)) {
				ByteBuffer buffer = ByteBuffer.allocate(8192); // 8 KB buffer
			while (channel.read(buffer) != -1) {
				buffer.flip();
				digest.update(buffer);
				buffer.clear();
			}
			return digest.digest();
		}
	}

	/**
	 * 将字节数组转换为String类型哈希值
	 * @param bytes 字节数组
	 * @return 哈希值
	 */
	private static String bytesToHex(byte[] bytes) {
		StringBuilder result = new StringBuilder();
		for (byte b : bytes) {
			result.append(String.format("%02x", b));
		}
		return result.toString();
	}

	public static void main(String[] args) {
		String filePath = "D:\\bfd71f584d9645b0a5e3d7a465119f0c.pdf";
		try {
			byte[] sha256 = calculateSHA256(filePath);
			String sha256Hex = bytesToHex(sha256);
			System.out.println("SHA256: " + sha256Hex);
		} catch (IOException | NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

响应结果:(这里的结果是我自己再测试的时候生成的)

SHA256: cffebd06c485d17b8a93308e1e39cc4c1636444b762c9c153ba8b29022392b98


作者:筱白爱学习!!

欢迎关注转发评论点赞沟通,您的支持是筱白的动力!

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

筱白爱学习

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

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

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

打赏作者

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

抵扣说明:

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

余额充值