summaryrefslogtreecommitdiffstats
path: root/passwd.c
blob: 727261f9a9b4ca66517b2fa7cf36e8239f899c39 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* passwd.c  --  Generates a SHA512 hash of a clear-text password
 *
 *  GPLv2 - Copyright (C) 2008  David Sommerseth <dazo@users.sourceforge.net>
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; version 2
 *  of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

#include "eurephia_nullsafe.h"
#include "sha512.h"

char *_passwdhash(const char *pwd, const char *file, const int line) {
        SHA512Context sha;
        uint8_t sha_res[SHA512_HASH_SIZE];
        char *ret = NULL, *ptr = NULL;
        unsigned len = 0, i;
        
        len = strlen_nullsafe(pwd);
        if( (pwd == NULL) && (len == 0) ) {
                return NULL;
        }
        
        // Generate SHA512 hash of password
        memset(&sha, 0, sizeof(SHA512Context));
        memset(&sha_res, 0, sizeof(sha_res));
        SHA512Init(&sha);
        SHA512Update(&sha, pwd, len);
        SHA512Final(&sha, sha_res);

        // Allocate memory for the return buffer
#ifdef MEMWATCH
        ret = (char *) mwMalloc((SHA512_HASH_SIZE*2)+3, file, line);
#else
        ret = (char *) malloc((SHA512_HASH_SIZE*2)+3);
#endif
        memset(ret, 0,(SHA512_HASH_SIZE*2)+3);
        ptr = ret;
        
        // Generate a readable string of the hash
        for( i = 0; i < SHA512_HASH_SIZE; i++ ) {
                sprintf(ptr, "%02x", sha_res[i]);
                ptr += 2;
        }
        
        // Cleanup - remove hash data from memory
        memset(&sha, 0, sizeof(SHA512Context));
        memset(&sha_res, 0, sizeof(sha_res));

        return ret;
}