Programing

C ++에서 파일의 MD5 해시를 얻는 방법은 무엇입니까?

crosscheck 2020. 11. 2. 07:39
반응형

C ++에서 파일의 MD5 해시를 얻는 방법은 무엇입니까?


파일 경로가 있습니다. MD5 해시를 어떻게 구할 수 있습니까?


다음 md5sum은 명령 줄에 지정된 파일의 MD5를 계산하고 표시하는 명령 의 간단한 구현입니다 . gcc md5.c -o md5 -lssl작동 하려면 OpenSSL 라이브러리 ( )에 링크 되어야합니다. 순수 C이지만 C ++ 애플리케이션에 쉽게 적용 할 수 있어야합니다.

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <openssl/md5.h>

unsigned char result[MD5_DIGEST_LENGTH];

// Print the MD5 sum as hex-digits.
void print_md5_sum(unsigned char* md) {
    int i;
    for(i=0; i <MD5_DIGEST_LENGTH; i++) {
            printf("%02x",md[i]);
    }
}

// Get the size of the file by its file descriptor
unsigned long get_size_by_fd(int fd) {
    struct stat statbuf;
    if(fstat(fd, &statbuf) < 0) exit(-1);
    return statbuf.st_size;
}

int main(int argc, char *argv[]) {
    int file_descript;
    unsigned long file_size;
    char* file_buffer;

    if(argc != 2) { 
            printf("Must specify the file\n");
            exit(-1);
    }
    printf("using file:\t%s\n", argv[1]);

    file_descript = open(argv[1], O_RDONLY);
    if(file_descript < 0) exit(-1);

    file_size = get_size_by_fd(file_descript);
    printf("file size:\t%lu\n", file_size);

    file_buffer = mmap(0, file_size, PROT_READ, MAP_SHARED, file_descript, 0);
    MD5((unsigned char*) file_buffer, file_size, result);
    munmap(file_buffer, file_size); 

    print_md5_sum(result);
    printf("  %s\n", argv[1]);

    return 0;
}

MD5 알고리즘을 직접 구현하거나 (예는 웹 전체에 있음) OpenSSL 라이브러리에 연결하고 OpenSSL의 다이제스트 기능을 사용할 수 있습니다. 다음은 바이트 배열의 MD5를 가져 오는 예입니다.

#include <openssl/md5.h>
QByteArray AESWrapper::md5 ( const QByteArray& data) {
    unsigned char * tmp_hash;
    tmp_hash = MD5((const unsigned char*)data.constData(), data.length(), NULL);
    return QByteArray((const char*)tmp_hash, MD5_DIGEST_LENGTH);
}

QFile file("bigimage.jpg");

if (file.open(QIODevice::ReadOnly))
{
    QByteArray fileData = file.readAll();

    QByteArray hashData = QCryptographicHash::hash(fileData,QCryptographicHash::Md5); // or QCryptographicHash::Sha1
    qDebug() << hashData.toHex();  // 0e0c2180dfd784dd84423b00af86e2fc

}

지금 바로이 작업을 수행해야했고 C ++ 11, 부스트 및 openssl에 적합한 크로스 플랫폼 솔루션이 필요했습니다. 나는 D' Nabre의 솔루션을 시작점으로 삼아 다음과 같이 요약 했습니다.

#include <openssl/md5.h>
#include <iomanip>
#include <sstream>
#include <boost/iostreams/device/mapped_file.hpp>

const std::string md5_from_file(const std::string& path)
{
    unsigned char result[MD5_DIGEST_LENGTH];
    boost::iostreams::mapped_file_source src(path);
    MD5((unsigned char*)src.data(), src.size(), result);

    std::ostringstream sout;
    sout<<std::hex<<std::setfill('0');
    for(auto c: result) sout<<std::setw(2)<<(int)c;

    return sout.str();
}

빠른 테스트 실행 파일은 다음을 보여줍니다.

#include <iostream>

int main(int argc, char *argv[]) {
    if(argc != 2) {
        std::cerr<<"Must specify the file\n";
        exit(-1);
    }
    std::cout<<md5_from_file(argv[1])<<"  "<<argv[1]<<std::endl;
    return 0;
}

연결 참고 사항 : Linux : -lcrypto -lboost_iostreamsWindows :-DBOOST_ALL_DYN_LINK libeay32.lib ssleay32.lib


중복 라벨이 잘못 지정되어 ' https://stackoverflow.com/questions/4393017/md5-implementation-in-c ' 에서 리디렉션 된 사용자

여기에있는 예제가 작동합니다.

http://www.zedwood.com/article/cpp-md5-function

VC ++ 2010에서 컴파일하는 경우 main.cpp를 다음과 같이 변경해야합니다.

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    std::string Temp =  md5("The quick brown fox jumps over the lazy dog");
    cout << Temp.c_str() << endl;

    return 0;
}

여기서이 페이지의 질문에 답하기 위해 문자열 대신 char * 배열로 읽으려면 MD5 클래스를 약간 변경해야합니다.

편집하다:

분명히 MD5 라이브러리를 수정하는 것은 명확하지 않습니다. 전체 VC ++ 2010 솔루션이 char *를 포함하는 편의를 위해 여기에 있습니다.

https://github.com/alm4096/MD5-Hash-Example-VS

여기에 약간의 설명이 있습니다.

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include <fstream>
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    //Start opening your file
    ifstream inBigArrayfile;
    inBigArrayfile.open ("Data.dat", std::ios::binary | std::ios::in);

    //Find length of file
    inBigArrayfile.seekg (0, std::ios::end);
    long Length = inBigArrayfile.tellg();
    inBigArrayfile.seekg (0, std::ios::beg);    

    //read in the data from your file
    char * InFileData = new char[Length];
    inBigArrayfile.read(InFileData,Length);

    //Calculate MD5 hash
    std::string Temp =  md5(InFileData,Length);
    cout << Temp.c_str() << endl;

    //Clean up
    delete [] InFileData;

    return 0;
}

MD5 라이브러리에 다음을 추가했습니다.

MD5.cpp :

MD5::MD5(char * Input, long length)
{
  init();
  update(Input, length);
  finalize();
}

MD5.h :

std::string md5(char * Input, long length);

이 파일 http://people.csail.mit.edu/rivest/Md5.c를 사용합니다 .


나는 이전에이 작업과 다른 작업을 수행하기 위해 Botan 을 사용했습니다. AraK는 Crypto ++를 지적했습니다. 두 라이브러리 모두 완벽하게 유효하다고 생각합니다. 이제 그것은 당신에게 달려 있습니다 :-).


John Walker의 구현소스 와 함께 제공 됩니다 .


http://256stuff.com/sources/md5/ 에 사용 예제와 함께 예쁜 라이브러리 가 있습니다. 이것은 MD5를위한 가장 간단한 라이브러리입니다.


Crypto ++를 사용하여 다음을 수행 할 수 있습니다.

#include <sha.h>
#include <iostream> 

SHA256 sha; 
while ( !f.eof() ) { 
   char buff[4096];
   int numchars = f.read(...); 
   sha.Update(buff, numchars); 
}
char hash[size]; 
sha.Final(hash); 
cout << hash <<endl; 

I have a need for something very similar, because I can't read in multi-gigabyte files just to compute a hash. In theory I could memory map them, but I have to support 32bit platforms - that's still problematic for large files.


A rework of impementation by @D'Nabre for C++. Don't forget to compile with -lcrypto at the end: gcc md5.c -o md5 -lcrypto.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

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

unsigned char result[MD5_DIGEST_LENGTH];

// function to print MD5 correctly
void printMD5(unsigned char* md, long size = MD5_DIGEST_LENGTH) {
    for (int i=0; i<size; i++) {
        cout<< hex << setw(2) << setfill('0') << (int) md[i];
    }
}

int main(int argc, char *argv[]) {

if(argc != 2) {
    cout << "Specify the file..." << endl;
    return 0;
}

ifstream::pos_type fileSize;
char * memBlock;

ifstream file (argv[1], ios::ate);

//check if opened
if (file.is_open() ) { cout<< "Using file\t"<< argv[1]<<endl; }
else {
    cout<< "Unnable to open\t"<< argv[1]<<endl;
    return 0;
}

//get file size & copy file to memory
//~ file.seekg(-1,ios::end); // exludes EOF
fileSize = file.tellg();
cout << "File size \t"<< fileSize << endl;
memBlock = new char[fileSize];
file.seekg(0,ios::beg);
file.read(memBlock, fileSize);
file.close();

//get md5 sum
MD5((unsigned char*) memBlock, fileSize, result);

//~ cout << "MD5_DIGEST_LENGTH = "<< MD5_DIGEST_LENGTH << endl;
printMD5(result);
cout<<endl;

return 0;
}

md5.h also have MD5_* functions very useful for big file

#include <openssl/md5.h>
#include <fstream>
.......

std::ifstream file(filename, std::ifstream::binary);
MD5_CTX md5Context;
MD5_Init(&md5Context);
char buf[1024 * 16];
while (file.good()) {
    file.read(buf, sizeof(buf));
    MD5_Update(&md5Context, buf, file.gcount());
}
unsigned char result[MD5_DIGEST_LENGTH];
MD5_Final(result, &md5Context);

Very simple, isn`t it? Convertion to string also very simple:

#include <sstream>
#include <iomanip>
.......

std::stringstream md5string;
md5string << std::hex << std::uppercase << std::setfill('0');
for (const auto &byte: result)
    md5string << std::setw(2) << (int)byte;

return md5string.str();

참고URL : https://stackoverflow.com/questions/1220046/how-to-get-the-md5-hash-of-a-file-in-c

반응형