Is there a standard way to represent the SHA1 hash as a C string and how to convert it?

This question is about creating a SHA-1 hash from an array of data in C using OpenSSL .

It returns an array of 20 bytes containing a hash. Is there a standard way to represent data in string form, and not in binary format?

If so, is there a function in OpenSSL to convert to the specified string format?

If not, how to do it? Of course, I can come up with my own encoding, use base64 or not, but is there any canonical format?

+6
c ++ c openssl hash
source share
4 answers

Usually, hashes are represented as a sequence of hexadecimal digits (of course, two bytes each). You can write code to easily write such a thing using ostringstream with right modifiers:

 #include <string> #include <sstream> #include <iomanip> std::string GetHexRepresentation(const unsigned char * Bytes, size_t Length) { std::ostringstream os; os.fill('0'); os<<std::hex; for(const unsigned char * ptr=Bytes;ptr<Bytes+Length;ptr++) os<<std::setw(2)<<(unsigned int)*ptr; return os.str(); } 
+12
source share

The standard way to represent hashes is in hexadecimal strings.
In C, you can use printf("%02x", byte) to get the hexadecimal representation of each byte.

An example for MD5 should be easy to adapt it for SHA:

http://en.literateprograms.org/MD5_sum_ (C, _OpenSSL)

+3
source share

Here is an example for C:

 //function void convertSHA1BinaryToCharStr(const unsigned char * const hashbin, char * const hashstr) { for(int i = 0; i<20; ++i) { sprintf(&hashstr[i*2], "%02X", hashbin[i]); } hashstr[40]=0; } //Example call. hashbin is the 20byte hash array. char hashstr[41]; convertSHA1BinaryToCharStr(hashbin, hashstr); printf("%s\n", hashstr); 
+2
source share

Privacy Enhanced Mail (or PEM) seems to have set the standard for storing textual representations of cryptographic data. PEM stores the actual binary fragment in Base64, but also has a text header and footer.

0
source share

All Articles