Md5加密工具(附文件MD5值计算方法)
发布日期:2021-06-30 18:39:38 浏览次数:3 分类:技术文章

本文共 2469 字,大约阅读时间需要 8 分钟。

import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class Md5Utils {
/** * @param path * 文件的路径 * @return * 文件的MD5值 */ public static String getFileMD5(String path){ StringBuilder mess = new StringBuilder(); try { FileInputStream fis = new FileInputStream(new File(path)); //获取MD5加密器 MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[10240]; int len = fis.read(buffer); while (len != -1) { md.update(buffer, 0, len); //继续读取 len = fis.read(buffer); } byte[] digest = md.digest(); for (byte b : digest){ //把每个字节转成16进制数 int d = b & 0xff;// 0x000000ff String hexString = Integer.toHexString(d); if (hexString.length() == 1) {
//字节的高4位为0 hexString = "0" + hexString; } hexString = hexString.toUpperCase(); mess.append(hexString);//把每个字节对应的2位十六进制数当成字符串拼接一起 } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mess + ""; } public static String md5(String str){ StringBuilder mess = new StringBuilder(); try { //获取MD5加密器 MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = str.getBytes(); byte[] digest = md.digest(bytes); for (byte b : digest){ //把每个字节转成16进制数 int d = b & 0xff;// 0x000000ff String hexString = Integer.toHexString(d); if (hexString.length() == 1) {
//字节的高4位为0 hexString = "0" + hexString; } mess.append(hexString);//把每个字节对应的2位十六进制数当成字符串拼接一起 } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mess + ""; }}

转载地址:https://linqiarui.blog.csdn.net/article/details/51175064 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:得到缓存及清理缓存
下一篇:自定义的环形进度条样式

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月23日 05时15分01秒