简体   繁体   中英

How to convert ascii encoded hash to hex encoded one?

So I am using this hash hashing code to genrate a SHA1 hash. And it the hash function returns a std::string which is ASCII encoded and so the hash takes up 40 bytes of memory. And I need to store the hash in 20 byte(and 40 hex character) with hex encoding. How is it done?

At the end of the final method there is some code which writes the digest array as a hex string.

inline std::string SHA1::final()
{
    ...

    /* Hex std::string */
    std::ostringstream result;
    for (size_t i = 0; i < sizeof(digest) / sizeof(digest[0]); i++)
    {
        result << std::hex << std::setfill('0') << std::setw(8);
        result << digest[i];
    }

    /* Reset for next run */
    reset(digest, buffer, transforms);

    return result.str();
}

To get a binary string instead simply replace this code with binary I/O

inline std::string SHA1::final()
{
    ...

    /* Binary std::string */
    std::ostringstream result;
    result.write(reinterpret_cast<char*>(digest), sizeof digest);

    /* Reset for next run */
    reset(digest, buffer, transforms);

    return result.str();
}

Note, as always when writing multibyte integers in binary, there is a potential endianess issue here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM