1

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.
Mutantoe
  • 703
  • 8
  • 20

1 Answers1

2

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 (i.e. dealing only in literal types or constexpr user types composed therefrom).

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

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • I mean that when I open the .exe in Notepad (oe), I can't see the strings, only a hash. Could I try to un-golf the [tweetable version](https://twitter.com/TweetFIPS202)? – Mutantoe Mar 10 '16 at 15:09
  • 2
    if you successfully implement SHA3 hashing as constexpr then in an optimised build, the original strings won't be there - only the hash (at least in clang). – Richard Hodges Mar 10 '16 at 15:21