使用MD5_HashList验证文件完整性_定时检测文件修改

#include <iostream>
#include <openssl/md5.h>
#include <fstream>
#include <thread>
using namespace std;

string GetFileListHash(string filepath)
{
    string hash;
    //以二进制方式打开文件
    ifstream ifs(filepath, ios::binary);
    if (!ifs)
        return hash;
    //一次读取多少字节的文件
    int block_size = 128;
    
    //文件读取buf
    unsigned char buf[1024] = { 0 };

    //hash输出
    unsigned char out[1024] = { 0 };

    while (!ifs.eof())
    {
        ifs.read((char*)buf, block_size);
        int read_size = ifs.gcount();
        if (read_size <= 0)break;
        MD5(buf, read_size, out);
        hash.insert(hash.end(), out, out + 16);
    }
    ifs.close();
    MD5((unsigned char*)hash.data(), hash.size(), out);
    return string(out,out+16);
}

void PrintHex(string data)
{
    for (auto c : data)
        cout << hex << (int)(unsigned char)c;
    cout << endl;
}

int main(int argc, char* argv[])
{
    cout << "Test  Hash!" << endl;
    unsigned char data[] = "测试md5数据";
    unsigned char out[1024] = { 0 };
    int len = sizeof(data);
    MD5_CTX c;
    MD5_Init(&c);
    MD5_Update(&c, data, len);
    MD5_Final(out, &c);
    for (int i = 0; i < 16; i++)
        cout << hex << (int)out[i];
    cout << endl;
    data[1] = 9;
    MD5(data, len, out);
    for (int i = 0; i < 16; i++)
        cout << hex << (int)out[i];
    cout << endl;
    string filepath = "../../src/test_hash/test_hash.cpp";
    auto hash1 = GetFileListHash(filepath);
    PrintHex(hash1);
    //验证文件完整性
    for (;;)
    {
        auto hash = GetFileListHash(filepath);
        if (hash != hash1)
        { 
            cout << "文件被修改" ;
            PrintHex(hash);
        }   
        this_thread::sleep_for(1s);
    }



    getchar();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值