måndag 1 oktober 2012

SHA1 calculation using boost

Here is how to calculate a SHA1 hash using boost.
/*
  sha1 digest function, using boost.
  By Paul Dreik 20121001 http://www.pauldreik.se/
  License: GPLv2 or later, at your option.
*/
#include <fstream>
#include <iostream>
#include <iomanip>
#include <boost/uuid/sha1.hpp>

int main(int argc, char* argv[]) {
  if(argc<2) {
    std::cerr<<"Supply file name as the first argument.\n";
    return -1;
  }
  
  //open the file
  std::ifstream ifs(argv[1],std::ios::binary);
  
  if(!ifs.good()) {
    std::cerr<<"bad file\n";
    return -2;
  }

  boost::uuids::detail::sha1 sha1;
  unsigned int hash[5];
  char buf[1024];
  while(ifs.good()) {
    ifs.read(buf,sizeof(buf));
    sha1.process_bytes(buf,ifs.gcount());
  }
  if(!ifs.eof()) {
    std::cerr<<"not at eof\n";
    return -3;
  }
  ifs.close();
  sha1.get_digest(hash);
  std::cout<<std::hex<<std::setfill('0')<<std::setw(sizeof(int)*2);
  for(std::size_t i=0; i<sizeof(hash)/sizeof(hash[0]); ++i) {
    std::cout<<hash[i];
  }
  std::cout<<"  "<<argv[1]<<std::endl;
  return 0;
}