Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hash std::string?

Tags:

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?

like image 505
Septagram Avatar asked Nov 06 '11 18:11

Septagram


People also ask

How do you hash a string?

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 ) ).

Is STD hash unique?

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.

What is hashable C++?

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.


2 Answers

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++".

like image 54
Seth Carnegie Avatar answered Oct 12 '22 04:10

Seth Carnegie


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.

like image 28
Ou Wei Avatar answered Oct 12 '22 04:10

Ou Wei