summaryrefslogtreecommitdiff
path: root/src/crypt_sha256.c
blob: eff5eac931a806385a774572c44dcbf9e19ce632 (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
68
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <openssl/sha.h>
#include <openssl/evp.h>

#define RAND_FILE		"/dev/random"
#define SHA_STR			"{SSHA256}"

/* string length */
#define LEN_PASSWD_MIN		8
#define LEN_PASSWD_MAX		64
#define LEN_SALT		16
#define LEN_BUFFER		LEN_SALT + SHA256_DIGEST_LENGTH
#define LEN_ENC64		64
#define	LEN_SHA_STR		9
#define LEN_FINAL_PASSWD	LEN_ENC64 + LEN_SHA_STR

char* get_crypt_sha256(char *p)
{
	int rand_fd;
	ssize_t size;
	size_t len = strlen(p);
	unsigned char *salt;
	unsigned char passwd_buff[LEN_BUFFER];
	unsigned char sha_pwd[SHA256_DIGEST_LENGTH];
	unsigned char enc64_pwd[LEN_ENC64];
	char *final_pwd;

	salt = (unsigned char*) malloc(len + LEN_SALT);
	rand_fd = open(RAND_FILE, O_RDONLY);
	if (rand_fd < 0) {
		fprintf(stderr, "impossible to open " RAND_FILE "\n");
		memset(p, 0, len);
		exit(EXIT_FAILURE);
	}

	size = read(rand_fd, salt+len, LEN_SALT);
	close(rand_fd);
	if (size != LEN_SALT) {
		fprintf(stderr, "failed to read from " RAND_FILE "\n");
		memset(p, 0, len);
		exit(EXIT_FAILURE);
	}

	memcpy(salt, p, len);

	SHA256(salt, len + LEN_SALT, sha_pwd);

	memcpy(passwd_buff, sha_pwd, SHA256_DIGEST_LENGTH);
	memcpy(passwd_buff + SHA256_DIGEST_LENGTH, salt+len, LEN_SALT);

	/* clear plaintext passwd copy */
	memset(salt, 0, len + LEN_SALT);
	free(salt);

	EVP_EncodeBlock(enc64_pwd, passwd_buff,
				SHA256_DIGEST_LENGTH + LEN_SALT);


	final_pwd = (char*) malloc (LEN_FINAL_PASSWD + 1);
	memcpy(final_pwd, SHA_STR, LEN_SHA_STR);
	memcpy(final_pwd+LEN_SHA_STR, enc64_pwd, LEN_ENC64);
	final_pwd[LEN_FINAL_PASSWD] = '\0';

	return final_pwd;
}