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

该代码示例演示了如何利用MD5哈希算法计算字符串和文件的哈希值,用于数据完整性校验。首先,定义了一个`GetFileListHash`函数,该函数读取文件并计算其MD5哈希。然后,通过`PrintHex`函数打印十六进制哈希值。在`main`函数中,展示了对内存数据和文件的MD5计算,并实时监控文件是否被修改,如果被修改则输出新的哈希值。
摘要由CSDN通过智能技术生成
#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值