Debian Codegraph @

modules/crypto/pbkdf2.c

raw
1 /*
2 * Copyright (c) 2012 William Pitcock <[email protected]>.
3 *
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
9 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
10 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
11 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
12 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
13 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
14 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
15 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
16 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
17 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
18 * POSSIBILITY OF SUCH DAMAGE.
19 */
20
21 #include "atheme.h"
22
23 #ifdef HAVE_OPENSSL
24
25 DECLARE_MODULE_V1("crypto/pbkdf2", false, _modinit, _moddeinit, PACKAGE_VERSION, VENDOR_STRING);
26
27 #include <openssl/evp.h>
28 #include <openssl/sha.h>
29 #include <openssl/hmac.h>
30
31 #define ROUNDS (128000)
32 #define SALTLEN (16)
33
34 static const char *pbkdf2_salt(void)
35 {
36 static char buf[SALTLEN + 1];
37 char *randstr = random_string(SALTLEN);
38
39 mowgli_strlcpy(buf, randstr, sizeof buf);
40
41 free(randstr);
42
43 return buf;
44 }
45
46 static const char *pbkdf2_crypt(const char *key, const char *salt)
47 {
48 static char outbuf[PASSLEN];
49 static unsigned char digestbuf[SHA512_DIGEST_LENGTH];
50 int res, iter;
51
52 if (strlen(salt) < SALTLEN)
53 salt = pbkdf2_salt();
54
55 memcpy(outbuf, salt, SALTLEN);
56
57 res = PKCS5_PBKDF2_HMAC(key, strlen(key), (const unsigned char *)salt, SALTLEN, ROUNDS, EVP_sha512(), SHA512_DIGEST_LENGTH, digestbuf);
58
59 for (iter = 0; iter < SHA512_DIGEST_LENGTH; iter++)
60 sprintf(outbuf + SALTLEN + (iter * 2), "%02x", 255 & digestbuf[iter]);
61
62 return outbuf;
63 }
64
65 static crypt_impl_t pbkdf2_crypt_impl = {
66 .id = "pbkdf2",
67 .crypt = &pbkdf2_crypt,
68 .salt = &pbkdf2_salt
69 };
70
71 void _modinit(module_t *m)
72 {
73 crypt_register(&pbkdf2_crypt_impl);
74 }
75
76 void _moddeinit(module_unload_intent_t intent)
77 {
78 crypt_unregister(&pbkdf2_crypt_impl);
79 }
80
81 #endif