1 /*
2  * Copyright (C) 2011 Emweb bv, Herent, Belgium.
3  *
4  * See the LICENSE file for terms of use.
5  */
6 
7 #include <string>
8 
9 #include "Wt/WLogger.h"
10 #include "AuthUtils.h"
11 #include "HashFunction.h"
12 #include "PasswordHash.h"
13 #include "PasswordVerifier.h"
14 
15 namespace Wt {
16 
17 LOGGER("Auth.PasswordVerifier");
18 
19   namespace Auth {
20 
PasswordVerifier()21 PasswordVerifier::PasswordVerifier()
22   : saltLength_(12)
23 { }
24 
~PasswordVerifier()25 PasswordVerifier::~PasswordVerifier()
26 { }
27 
addHashFunction(std::unique_ptr<HashFunction> function)28 void PasswordVerifier::addHashFunction(std::unique_ptr<HashFunction> function)
29 {
30   hashFunctions_.push_back(std::move(function));
31 }
32 
hashFunctions()33 const std::vector<HashFunction *> PasswordVerifier::hashFunctions() const
34 {
35   std::vector<HashFunction *> result;
36   for (auto &hashFunction : hashFunctions_)
37     result.push_back(hashFunction.get());
38   return result;
39 }
40 
needsUpdate(const PasswordHash & hash)41 bool PasswordVerifier::needsUpdate(const PasswordHash& hash) const
42 {
43   return hash.function() != hashFunctions_[0]->name();
44 }
45 
hashPassword(const WString & password)46 PasswordHash PasswordVerifier::hashPassword(const WString& password) const
47 {
48   std::string msg = password.toUTF8();
49   std::string salt = Utils::createSalt(saltLength_);
50   salt = Utils::encodeAscii(salt);
51 
52   const HashFunction& f = *hashFunctions_[0];
53   std::string hash = f.compute(msg, salt);
54   return PasswordHash(f.name(), salt, hash);
55 }
56 
verify(const WString & password,const PasswordHash & hash)57 bool PasswordVerifier::verify(const WString& password,
58 			      const PasswordHash& hash) const
59 {
60   for (unsigned i = 0; i < hashFunctions_.size(); ++i) {
61     const HashFunction& f = *hashFunctions_[i];
62 
63     if (f.name() == hash.function())
64       return f.verify(password.toUTF8(), hash.salt(), hash.value());
65   }
66 
67   LOG_ERROR("verify() no hash configured for " << hash.function());
68 
69   return false;
70 }
71 
72   }
73 }
74