前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java中对文件进行MD5加密

Java中对文件进行MD5加密

作者头像
泰坦HW
发布2020-07-22 16:19:22
4.6K0
发布2020-07-22 16:19:22
举报
文章被收录于专栏:Titan笔记Titan笔记Titan笔记

前言

今天一个朋友的朋友的老师让他实现对文件的MD5加密校验,他找到了我的这个朋友,我的这个朋友找到了我。

之前用Python或者PHP很简单的就能实现这个东西,但是毕竟最近在深入研究Java,于是用Java写了一个MD5加密获得信息摘要的工具。

相关思路

用JDK中自带的Security包中的MessageDigest类可以实现MD5算法。所以基本的实现流程是 选择文件 -> 读取二进制流 -> MD5信息摘要 -> 转换为String返回输出。

代码

Main.java

import java.io.File;
import java.util.Scanner;

/*
A tool to get the MD5 of a File.
Author: Titan
 */
public class Main {

    public static void main(String[] args) {
        File file = null;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please input the file name.");
        String fileName = scanner.nextLine();
        file = new File(fileName);
        // Jude if the file is exist
        if (!file.isFile()) {
            System.out.println("File Not Found!");
            System.exit(-1);
        }
        // Handle the MD5 Operation
        Handler handler = new Handler(file);
        // Get MD5
        String md5Text = handler.getMD5();
        if (md5Text != null) {
            System.out.println("Get the MD5 Successfully");
            System.out.println("File Name: " + fileName);
            System.out.println("MD5 Text: " + md5Text);
        } else {
            System.out.println("Get MD5 Failed. ");
        }
    }
}

Handler.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Handler {
    private final byte[] buffer = new byte[1024];
    private MessageDigest md5 = null;
    private File file = null;

    public Handler(File file) {
        if (!file.isFile()) {
            System.out.println("File not found!");
        }
        try {
            this.md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.println("MD5 Method Error!");
        }
        this.file = file;
    }

    public String getMD5() {
        int length = 0;
        try (FileInputStream inputStream = new FileInputStream(file)) {
            while ((length = inputStream.read(buffer)) != -1) {
                md5.update(buffer, 0, length);
            }
            return new BigInteger(1, md5.digest()).toString(16);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020年04月22日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 相关思路
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档