MD5加密防止文件篡改
1、读取文件
public static String readFileByBytes(String fileName) {
StringBuffer sb = new StringBuffer();
try {
File file = new File(fileName);
InputStream in = null;
if (file.isFile() && file.exists()) { //判断文件是否存在
// 一次读多个字节
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();
}
}
以上是我们调用文件的方法,之后在main方法中定义文件的位置,然后进行MD5加密并输出
public static void main(String[] args) {
//readFileBytes中是文件所在位置
String content=readFileByBytes("C:\\Users\\lenovo\\Desktop\\123.txt");
System.out.println(content);
try {
System.out.println(md52(content));
} catch (Exception e) {
e.printStackTrace();
}
}
调用MD5方法
// 不带秘钥加密
public static String md52(String text) throws Exception {
// 加密后的字符串
String md5str = DigestUtils.md5Hex(text);
return md5str;
}
输出的结果:
我们对文件内容进行修改
通过这种方法,我们就可以判断我们的文件是否被篡改