I'm creating a simple hashing program and wish to use the SHA hash in
it. I was wondering if there was an easy way to do that. In Ruby you
can just say:
require "Digest"
sha_hex = Digest::SHA512.hexdigest("some string")
print sha_hex
Is there a comparable way to do this in c++?
Not standard, but I've got "accumulators" which do this in my
library (
http://kanze.james.neuf.fr/code-en.html---they're in
the IO section). Basically you use the accumulator with the
standard function std::accumulate.
Note that the code is in fact a template, specialized on a
traits class specifying the hashing algorithm, so it won't
necessarily be the simplest to understand. And because of the
way std::accumulate is designed, you pay a performance penalty
for the elegance of use---I've fixed this in more recent
versions (with a really horrible hack---but it works, and the
user doesn't see it), but they're not on line yet.
The simplest use might be something like:
output << text
<< std::accumulate( text.begin(), text.end(),
SHA256Hasher() ) ;
This will append the calculated digest in hex to the end of the
text. Since Hasher has full value semantics, you can also
separate its use, passing the results of an earlier accumulate
to a second call to accumulate. There's also a Digest class
which captures the immediate value of a hasher, and supports all
of the usual operators so that it can be used in associative
collections, etc.
I would like to have the speed it offers instead of having to
wait for ruby.
If speed is critical, at least with the publicly available
version, you'll have to use the member functions of my Hasher:
SHA256Hasher h ;
h.append( text.begin(), text.end() ;
// ...
std::accumulate uses "h = h + *iter", which involves a lot of
copying. (As I said, more recent versions use a fairly ugly
hack to avoid this.)