MD5是一种常用的散列算法,它可以将任意长度的输入数据映射为一个128位的输出,这个输出就是一个固定长度的数字,通常用来校验数据的完整性,它的特点是不可逆,即无法从散列值反推出原来的数据。
相关思路
用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; } } }
文章评论