java:MD5加密字符串

本文介绍了一个使用Java实现的MD5加密工具类,该工具可以读取文件内容并将其转换为MD5密文。通过这个实用工具,用户可以方便地对指定路径下的文件进行加密处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

备份一个小程序。利用MD5加密文件,生成一个密文的源程序。非常好用。

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.*;

public class EncryptUtil
{
 /**
  *
  * @param filePath The full path of the file
  * @return
  * @throws Exception
  */
 public static String encrypt(String filePath) throws Exception
 {
  String inStr = getString(filePath);
  MessageDigest md = null;
  String out = null;

  try
  {
   md = MessageDigest.getInstance("MD5");
   byte[] digest = md.digest(inStr.getBytes());
   out = byte2hex(digest);
  }
  catch (NoSuchAlgorithmException e)
  {
   e.printStackTrace();
   throw e;
  }

  return out;
 }

 private static String byte2hex(byte[] b)
 {
  String hs = "";
  String stmp = "";
  for (int n = 0; n < b.length; n++)
  {
   stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
   if (stmp.length() == 1)
   {
    hs = hs + "0" + stmp;
   }
   else
   {
    hs = hs + stmp;
   }
  }
  return hs.toUpperCase();
 }

 private static String getString(String filePath) throws Exception
 {
  StringBuffer sbuf = new StringBuffer();
  try
  {
   FileReader fr = new FileReader(filePath);
   BufferedReader br = new BufferedReader(fr);

   String Line = br.readLine();

   while (Line != null)
   {
    sbuf.append(Line);
    sbuf.append("/r/n");    
    Line = br.readLine();
   }
   br.close();
   fr.close();
  }
  catch (Exception e)
  {
   e.printStackTrace();
   throw e;
  }
  //System.out.println(sbuf.toString());
  
  return sbuf.toString().trim();
 }

 public static void main(String[] args) throws Exception
 {
  if(args.length > 0)
  {
   String result = null;
   try
   {
    result = encrypt(args[0]);
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
   System.out.println(args[0] + " : " + result);
   //System.out.println(args[1] + " : " + encrypt(args[1])); 
  }
  else
  {
   System.out.println("the file does not exist");
  }
 }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值