MD5加密防止文件篡改

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;
		}

输出的结果:
在这里插入图片描述
我们对文件内容进行修改
在这里插入图片描述
通过这种方法,我们就可以判断我们的文件是否被篡改

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值