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?
For the conversion, we need a so-called hash function. The goal of it is to convert a string into an integer, the so-called hash of the string. The following condition has to hold: if two strings and are equal ( ), then also their hashes have to be equal ( hash ( s ) = hash ( t ) ).
That means you can only have 256 unique hashes of arbitrary inputs. Since you can definitely create more than 256 different strings, there is no way the hash would be unique for all possible strings.
A hash table is a data structure which is used to store key-value pairs. Hash function is used by hash table to compute an index into an array in which an element will be inserted or searched. This is a C++ program to Implement Hash Tables.
For a quick solution involving no external libraries, you can use hash<std::string>
to hash string
s. 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++".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With