lorem1213
lorem1213

Reputation: 464

How to read and write binary SHA1 digest from std::fstream

I need to read and write a hex encoded SHA1 value in the file. If I wanted to write C30A then I need to convert C30A into character array whose length is equal to half the length of the hashvalue since a byte can hold two hex characters; for C30A,

    char array[2];
    array[0] = 11000011=195;
    array[1] = 00001010=10;//which is an ascii for '\n'

If I wanted to write this char array I have done: filestream<<array;

Now when I want to read it from file how should I read it?

I tried doing

    std::string str;
    filestream>>str;

But it stops whenever it encounters whitespace characters like '\0','\r','\n' etc. And It always ends up reading only a portion of the hash, since there will be those character for sure.

What way should I go to read and write in this case?

Upvotes: 0

Views: 37

Answers (1)

Botje
Botje

Reputation: 30927

If there is nothing else in the file, know that a SHA1 digest is 160 bits, or 20 bytes:

string sha1(20, '\0');
filestream.read(sha1.data(), sha1.size());

Upvotes: 1

Related Questions