Panda3D
Loading...
Searching...
No Matches
password_hash.cxx
Go to the documentation of this file.
1/**
2 * PANDA 3D SOFTWARE
3 * Copyright (c) Carnegie Mellon University. All rights reserved.
4 *
5 * All use of this software is subject to the terms of the revised BSD
6 * license. You should have received a copy of this license along
7 * with this source code in a file named "LICENSE."
8 *
9 * @file password_hash.cxx
10 * @author drose
11 * @date 2004-09-01
12 */
13
14#include "password_hash.h"
15
16// The functions defined within this file rely on algorithms defined within
17// OpenSSL.
18#ifdef HAVE_OPENSSL
19
20#include "pnotify.h"
21#include <openssl/evp.h>
22#include "memoryHook.h"
23
24using std::string;
25
26/**
27 * Generates a non-reversible hash of a particular length based on an
28 * arbitrary password and a random salt. This is much stronger than the
29 * algorithm implemented by the standard Unix crypt().
30 *
31 * The resulting hash can be useful for two primary purposes: (1) the hash may
32 * be recorded to disk in lieu of recording plaintext passwords, for
33 * validation against a password entered by the user later (which should
34 * produce the same hash given a particular salt), or (2) the hash may be used
35 * as input to an encryption algorithm that requires a key of a particular
36 * length.
37 *
38 * password is the text password provided by a user.
39 *
40 * salt should be a string of arbitrary random bytes (it need not be
41 * crypotographically secure, just different for each different hash).
42 *
43 * iters should be a number in the thousands to indicate the number of times
44 * the hash algorithm should be applied. In general, iters should be chosen
45 * to make the computation as expensive as it can be and still be tolerable,
46 * to reduce the attractiveness of a brute-force attack.
47 *
48 * keylen is the length in bytes of the required key hash.
49 */
50string
51password_hash(const string &password, const string &salt,
52 int iters, int keylen) {
53 nassertr(iters > 0 && keylen > 0, string());
54 unsigned char *dk = (unsigned char *)PANDA_MALLOC_ARRAY(keylen);
55 int result =
56 PKCS5_PBKDF2_HMAC_SHA1((const char *)password.data(), password.length(),
57 (unsigned char *)salt.data(), salt.length(),
58 iters, keylen, dk);
59 nassertr(result > 0, string());
60
61 string hash((char *)dk, keylen);
62 PANDA_FREE_ARRAY(dk);
63 return hash;
64}
65
66
67
68#endif // HAVE_OPENSSL
PANDA 3D SOFTWARE Copyright (c) Carnegie Mellon University.
PANDA 3D SOFTWARE Copyright (c) Carnegie Mellon University.
PANDA 3D SOFTWARE Copyright (c) Carnegie Mellon University.