md5工具类

public class MD5Utils {
/**
* md5加密方法

* @param string
*            需要md5的字符串
*/
public static String md5(String string) {
try {
// 得到一个信息摘要器
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] result = digest.digest(string.getBytes());
StringBuffer buffer = new StringBuffer();
// 把没一个byte 做一个与运算 0xff;
for (byte b : result) {
// 与运算
int number = b & 0xff;// 加盐
String str = Integer.toHexString(number);
if (str.length() == 1) {
buffer.append("0");
}
buffer.append(str);
}


// 标准的md5加密后的结果
return buffer.toString();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}


/**
* MD5加密算法

* @param bytes
*            需要md5的字节数组
*/
public static String md5(byte[] bytes) {
if (bytes == null) {
return null;
}
StringBuffer sb = null;
try {
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] bs = digest.digest(bytes);
sb = new StringBuffer();
// 把每一个byte做一次 与运算 0ff
for (byte b : bs) {
int num = b & 0xff;
String str = Integer.toHexString(num);
if (str.length() == 1) {
sb.append("0");
}
sb.append(str);
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}


/**
* 对一个文件进行MD5加密操作

* @param filePath
*            需要md5的文件路径
*/
public static String md5File(String filePath) throws Exception {
if (filePath == null) {
throw new IllegalArgumentException("文件路径不能为空");
}


File file = new File(filePath);
MessageDigest digest = MessageDigest.getInstance("md5");
FileInputStream fin = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = fin.read(buffer)) != -1) {
digest.update(buffer, 0, len);
}
fin.close();

byte[] result = digest.digest();
StringBuffer sb = new StringBuffer();
// 把没一个byte 做一个与运算 0xff;
for (byte b : result) {
// 与运算
int number = b & 0xff;// 加盐
String str = Integer.toHexString(number);
if (str.length() == 1) {
sb.append("0");
}
sb.append(str);
}


// 标准的md5加密后的结果
return sb.toString();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值