什么是MD5
md5是一种信息摘要算法
,它可以从一个字符串或一个文件中按照一定的规则生成一个特殊的字符串,并且一个文件所对应的MD5摘要是固定的,当文件内容变化后,其MD5值也会不一样,因此,在应用中经常使用MD5值来验证一段数据有没有被篡改
。
什么是MD5加密
MD5加密一般指MD5。MD5信息摘要算法,一种被广泛使用的密码散列函数
,可以产生出一个128位(16字节)的散列值,用于确保信息传输完整一致。
MD5加密的使用
首先需要在pom.xml中添加相应的包依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.12</version>
</dependency>
package com.whc.wznoteserver2.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.codec.digest.DigestUtils;
public class TestMD5 {
public static void main(String[] args) {
String salt = "!@#";
String content=readFileByBytes("C:\\Users\\Administrator\\Desktop\\2.txt");
String md5 = DigestUtils.md5Hex(content);
System.out.println(md5);
//4aa1d36a56eb1884e2906ec376311c99--正确的md5
}
private static String md5(String mm,String salt) {
return DigestUtils.md5Hex(mm+salt);
}
/**
* 从文件读取内容
* @param fileName
* @return
*/
public static String readFileByBytes(String fileName) {
StringBuffer sb = new StringBuffer();
try {
File file = new File(fileName);
InputStream in = null;
if(file.isFile() && file.exists()) {//判断文件是否存在
//System.out.println("以字节为单位读取文件内容,一次读取多个字节");
//一次读多个字节
byte[] tempbytes = new byte[1024];
int byteread = 0;
in = new FileInputStream(file);
//读入多个字节到字节数组中,byteread为一次读入的字节数
while((byteread = in.read(tempbytes))!=-1) {
//System.out.write(tempbytes,0,byteread);
String str = new String(tempbytes,0,byteread);
sb.append(str);
}
}
}catch(Exception e) {
}finally {
return sb.toString();
}
}
}
本