今天一个朋友的朋友的老师让他实现对文件的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;
}
}
}