milo icon indicating copy to clipboard operation
milo copied to clipboard

MD5 calculation

Open ahoarau opened this issue 11 months ago • 3 comments

Hi, It's not clear to me if we can use milo to hash files on the disk. Also, I would very much appreciate an MD5 hashing function. Best,

ahoarau avatar Feb 28 '24 13:02 ahoarau

Minimal example how to calculate sha-256 hash of a file:


#include <iostream>
#include <fstream>

#include <milo/primitive/codec/apie.h>
#include <milo/primitive/codec/base.h>
#include <milo/primitive/hash/apie.h>
#include <milo/primitive/hash/sha.h>

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        std::cerr << "Error. Missing path argument.";
        return -1;
    }

    auto buffer = std::vector<char>(8192, 0);
    auto fstream = std::ifstream(argv[1], std::ifstream::binary);

    if (!fstream.is_open())
    {
        std::cerr << "Error. Could not open the file.\n";
        return -1;
    }

    auto hash = milo::primitive::hash::apie<milo::primitive::hash::sha_2_256<>>{};

    while (!fstream.eof())
    {
        fstream.read(buffer.data(), buffer.size());
        hash.update(buffer.data(), fstream.gcount());
    }

    auto digest = hash.digest();

    std::cout << milo::primitive::codec::encode<milo::primitive::codec::base_16<>, std::string>(digest) << std::endl;

    return 0;
}

milosob avatar Mar 06 '24 22:03 milosob

Excellent 👌 what do you think about adding MD5 next to all the sha ?

ahoarau avatar Mar 07 '24 10:03 ahoarau

Will consider it, meanwhile if speed is your concern note that on relatively new x86-64 cpus, 2017 and later, sha-160 and sha-256 can be hardware accelerated and in this library they are.

milosob avatar Mar 11 '24 00:03 milosob