简体   繁体   中英

Compile-time hashing with constexpr and CryptoPP

I am trying to hash some strings at compile time (they do not need to be retrieved) using the Crypto++ library and a constexpr function. This is the code I have so far:

constexpr const char* operator "" _SHA3_HASH(const char *input, unsigned int length){
    CryptoPP::SHA3_512 hash;
    byte digest [CryptoPP::SHA3_512::DIGESTSIZE];
    hash.CalculateDigest(digest, (byte*)input, length);
    return (const char*) digest;
}

To be used: std::string passwordHash="password1234"_SHA3_HASH

I don't think that there's a way I can get this to work since the CryptoPP::SHA3_512 class probably isn't literal-friendly. Is there a better (or working) alternative I can use?

Notes:

  • I would prefer to use Crypto++ library, if possible
  • SHA3 would be nice, but any secure hash will do
  • If I can't compile-time hash, what are my alternatives?
  • I've looked around at possible duplicates, but none appear to reveal any method for complex code in constexpr functions.
  • I'm using the built in compiler in Qt creator, which is MinGW 32 bit.

You say compile-time. Do you really mean that? That implies the user-defined string literal is declared constexpr which (AFIAK) is not possible (I have tried).

This leaves the route of re-implementing SHA3 hash as a constexpr template function with the following signature:

template<size_t N>
constexpr custom_digest sha3_hash(const char (&source)[N])
{
   // your constexpr-friendly code goes here
}

Bear in mind that every function called by your constexpr function must also be constexpr (ie dealing only in literal types or constexpr user types composed therefrom).

Yes, const char (&)[N] is a literal type.

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