简体   繁体   English

使用constexpr和CryptoPP进行编译时哈希

[英]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. 我正在尝试使用Crypto ++库和constexpr函数在编译时对某些字符串进行哈希处理(不需要检索它们)。 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 要使用: 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. 我不认为有什么办法可以CryptoPP::SHA3_512起作用,因为CryptoPP::SHA3_512类可能不是字面友好的。 Is there a better (or working) alternative I can use? 我可以使用更好(或可行)的替代方法吗?

Notes: 笔记:

  • I would prefer to use Crypto++ library, if possible 如果可能的话,我宁愿使用Crypto ++库
  • SHA3 would be nice, but any secure hash will do SHA3​​会很好,但是任何安全的哈希都可以
  • 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. 我已经研究了可能的重复项,但是似乎没有一个可以揭示constexpr函数中用于复杂代码的任何方法。
  • I'm using the built in compiler in Qt creator, which is MinGW 32 bit. 我正在Qt Creator中使用内置的编译器,它是MinGW 32位。

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). 这意味着将用户定义的字符串文字声明为constexpr (AFIAK)是不可能的(我已经尝试过)。

This leaves the route of re-implementing SHA3 hash as a constexpr template function with the following signature: 这留下了重新实现SHA3哈希作为具有以下签名的constexpr模板函数的途径:

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). 请记住,由constexpr函数调用的每个函数也必须是constexpr(即,仅处理文字类型或由其组成的constexpr用户类型)。

Yes, const char (&)[N] is a literal type. 是的, const char (&)[N]是文字类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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