How to hash std::string?

时光毁灭记忆、已成空白 提交于 2020-05-11 04:07:10

问题


I'm making a little utility to help me remember passwords by repetition. I'd like to enter password to be remembered only once every day and not before each session. Of course, I wouldn't store a password itself, but would gladly store its hash.

So, what are the easiest ways to get a hash from std::string using the C++ Standard Library?


回答1:


For a quick solution involving no external libraries, you can use hash<std::string> to hash strings. It's defined by including the header files hash_map or unordered_map (or some others too).

#include <string>
#include <unordered_map>

hash<string> hasher;

string s = "heyho";

size_t hash = hasher(s);

If you decide you want the added security of SHA, you don't have to download the large Crypto++ library if you don't need all its other features; there are plenty of standalone implementations on the internet, just search for "sha implementation c++".




回答2:


using c++11, you can:

#include <string>
#include <unordered_map>

std::size_t h1 = std::hash<std::string>{}("MyString");
std::size_t h2 = std::hash<double>{}(3.14159);

see more here.




回答3:


You can use the STL functor hash. See if your STL lib has it or not.

Note that this one returns a size_t, so range is numeric_limits<size_t>::min() numeric_limits<size_t>::max(). You'll have to use SHA or something if that's not acceptable..



来源:https://stackoverflow.com/questions/8029121/how-to-hash-stdstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!