C++ Library to handle BagIt structures. BagIt is a standard format to create transfer packages for digital preservation purposes. See https://en.wikipedia.org/wiki/BagIt for details http://andreas-romeyke.de
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
3.0 KiB

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include "checksum.hpp"
string string_of_algorithm( checksum_algorithms alg) {
switch( alg ) {
case md5: return string("md5");
case sha1: return string("sha1");
case sha256: return string("sha256");
}
}
string Checksum::checksum_of_file(string filepath, checksum_algorithms alg) {
ifstream file (filepath, ios::ate);
stringstream hex_result;
// cout << "processing file '" << filepath << "'" << endl;
if (file.is_open() ) {
ifstream::pos_type fileSize;
char * memBlock;
fileSize = file.tellg();
memBlock = new char[fileSize];
if (NULL != memBlock) {
file.seekg(0,ios::beg);
file.read(memBlock, fileSize);
switch ( alg ) {
case md5: {
unsigned char result[MD5_DIGEST_LENGTH];
MD5((unsigned char*) memBlock, fileSize, result);
for (int i=0; i<MD5_DIGEST_LENGTH; i++) {
hex_result<< hex << setw(2) << setfill('0') << (int) result[i];
}
break;
}
case sha1: {
unsigned char result[SHA_DIGEST_LENGTH];
SHA1((unsigned char*) memBlock, fileSize, result);
for (int i=0; i<SHA_DIGEST_LENGTH; i++) {
hex_result<< hex << setw(2) << setfill('0') << (int) result[i];
}
break;
}
case sha256: {
unsigned char result[SHA_DIGEST_LENGTH];
SHA256((unsigned char*) memBlock, fileSize, result);
for (int i=0; i<SHA_DIGEST_LENGTH; i++) {
hex_result<< hex << setw(2) << setfill('0') << (int) result[i];
}
break;
}
}
delete memBlock[];
// cout << "# # CHECKSUM for filepath '" << filepath << "' " << hex_result.str() << endl;
}else {
cout << "could not alloc memory" << endl;
}
file.close();
} else {
cout << "file '"<< filepath << "' could not be opened" << endl;
}
return hex_result.str();
}
oxum_t Checksum::oxum_of_file(string filepath) {
ifstream file (filepath, ios::ate);
oxum_t oxum;
//cout << "processing file '" << filepath << "'" << endl;
if (file.is_open() ) {
ifstream::pos_type fileSize;
fileSize = file.tellg();
oxum.octetcount = fileSize;
oxum.streamcount = 1;
file.close();
} else {
cout << "file '"<< filepath << "' could not be opened" << endl;
}
return oxum;
}
oxum_t Checksum::oxum_of_filelist( list<string> files) {
oxum_t oxum;
oxum.octetcount=0;
oxum.streamcount=0;
list<string>::iterator i;
for (i=files.begin(); i!= files.end(); i++) {
oxum_t tmp = this->oxum_of_file( *i );
oxum.octetcount+= tmp.octetcount;
oxum.streamcount+= tmp.streamcount;
}
return oxum;
}
// vim: set tabstop=4 softtabstop=0 expandtab shiftwidth=4 smarttab