Treat
Treat

Reputation: 192

sha1 function in cpp (C++)

Ill start by saying I dont know anything about c++ and I googled, there is nothing that can make me understand how to use SHA1 in C++. found this one though Objective C: SHA1 but its about objective c im not sure it is the same.

I need to do the following:

I habve a lot of files, i compile them by doing ./make.sh and in one file called server.cpp I need to SHA1 info_hash thats inserted in this part:

Csql_query(m_database, "insert into @files (info_hash, mtime, ctime)
 values (?, unix_timestamp(), unix_timestamp())").p(i.first).execute();

so I kinda think I need to do the following sha1(?). "?" isnt info_hash i need. i think it generates somewhere and "?" is a variable.

so please dont tell me to add any classes or something else, because i do NOT understand how to do that, if i need to add something in the beggining of the file, please tell me so.

Upvotes: 1

Views: 19860

Answers (4)

jhasse
jhasse

Reputation: 2593

If you have (header-only) Boost (v1.68+) available, there's a SHA1 implementation inside uuid:

#include <boost/uuid/detail/sha1.hpp>
#include <iomanip>
#include <iostream>
#include <sstream>

std::string sha1(const std::string& input) {
    boost::uuids::detail::sha1 sha1;
    sha1.process_bytes(input.data(), input.size());
    unsigned int digest[5];
    sha1.get_digest(digest);
    std::ostringstream hash;
    hash << std::hex << std::setfill('0');
    for (size_t i = 0; i < 5; ++i) {
        // Swap byte order because of Little Endian
        const char* tmp = reinterpret_cast<char*>(digest);
        hash << std::setw(2) << static_cast<int>(static_cast<uint8_t>(tmp[i * 4 + 3]))
             << std::setw(2) << static_cast<int>(static_cast<uint8_t>(tmp[i * 4 + 2]))
             << std::setw(2) << static_cast<int>(static_cast<uint8_t>(tmp[i * 4 + 1]))
             << std::setw(2) << static_cast<int>(static_cast<uint8_t>(tmp[i * 4]));
    }
    return hash.str();
}

int main() {
    std::cout << sha1("cat") << std::endl;
    // output: 9d989e8d27dc9e0ec3389fc855f142c3d40f0c50
}

Upvotes: 0

Martin Beckett
Martin Beckett

Reputation: 96109

Here is a library that implements SHA1() - there are probably better i.e. more efficient libraries but this has a good explanation of how to use it.

If you want to calculate the SHA1 of a file there is a Microsoft utility for that.

Upvotes: 0

Zan Lynx
Zan Lynx

Reputation: 54325

A good library for SHA1 and other functions is cryptopp.

Here is another question where the answer is cryptopp: Fast Cross-Platform C/C++ Hashing Library

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 993343

It looks like the .p(i.first) part already substitutes the value of i.first into the ? in your query. Presumably i.first would be a value appropriate for the info_hash column.

Without seeing more of your code, it's impossible to say for sure.

Upvotes: 1

Related Questions