Using cryptographic streams in C++

2019-02-15 05:43发布

问题:

I'd like to use some cryptographic operations (mainly integrty check hashsums). However I have problems with finding documentations of doing operations of such form:

bool read(std::istream &in) {
    hasher hv(in);
    // Do some operations on hv as if it was std::istream
    hash_type h = hv.finish ();
    hash_type h2 = read_hash(in);
    return h == h2;
}

PS. It may be different library provided it a) is GPL-3-compatible b) works on GNU/Linux

PPS. I don't insist on crypto++ however I would like to have IOStream-like behaviour for interoperability with other C++ libraries.

回答1:

Implement your own istream using crypto++.



回答2:

crypto++'s FileSource class takes std::istream& in the constructor, so it seems that you are done.

FileSource (std::istream &in, bool pumpAll, 
    BufferedTransformation *attachment=NULL)

EDIT

if you are asking how to use a hash function on istream in cryptopp, here's a sample taken from cryptopp wiki, modified by me for use with istream:

#include "sha.h"
#include "files.h"

std::string digest;

CryptoPP::SHA256 hash;

CryptoPP::FileSource(in, true,   // true here means consume all input at once 
   new CryptoPP::HashFilter(hash,
         new CryptoPP::StringSink(digest)));

std::cout << digest << std::endl;

This will read the stream in until eof, pass it through a hash filter and finally the result will enf up in the digest string.