summaryrefslogtreecommitdiffstats
path: root/crypto/pbkdf2.c
blob: c4ba7be5ef6902f43a1e5d44ff5505483b72b47a (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
 * (C) Copyright 2015 Jean-Christophe PLAGNIOL-VILLARD <plagnioj@jcrosoft.com>
 *
 * Under GPLv2 Only
 */

#include <common.h>
#include <malloc.h>
#include <errno.h>
#include <crypto/pbkdf2.h>

int pkcs5_pbkdf2_hmac(struct digest* d,
		      const unsigned char *pwd, size_t pwd_len,
		      const unsigned char *salt, size_t salt_len,
		      uint32_t iteration,
		      uint32_t key_len, unsigned char *key)
{
	int i, j, k;
	unsigned char cnt[4];
	uint32_t pass_len;
	unsigned char *tmpdgt;
	uint32_t d_len;
	int ret;

	if (!d)
		return -EINVAL;

	d_len = digest_length(d);
	tmpdgt = malloc(d_len);
	if (!tmpdgt)
		return -ENOMEM;

	i = 1;

	ret = digest_set_key(d, pwd, pwd_len);
	if (ret)
		goto err;

	while (key_len) {
		pass_len = min(key_len, d_len);
		cnt[0] = (i >> 24) & 0xff;
		cnt[1] = (i >> 16) & 0xff;
		cnt[2] = (i >> 8) & 0xff;
		cnt[3] = i & 0xff;
		ret = digest_init(d);
		if (ret)
			goto err;
		ret = digest_update(d, salt, salt_len);
		if (ret)
			goto err;
		ret = digest_update(d, cnt, 4);
		if (ret)
			goto err;
		ret = digest_final(d, tmpdgt);
		if (ret)
			goto err;

		memcpy(key, tmpdgt, pass_len);

		for (j = 1; j < iteration; j++) {
			ret = digest_digest(d, tmpdgt, d_len, tmpdgt);
			if (ret)
				goto err;

			for(k = 0; k < pass_len; k++)
				key[k] ^= tmpdgt[k];
		}

		key_len -= pass_len;
		key += pass_len;
		i++;
	}

	ret = 0;
err:
	free(tmpdgt);

	return ret;;
}

int pkcs5_pbkdf2_hmac_sha1(const unsigned char *pwd, size_t pwd_len,
			   const unsigned char *salt, size_t salt_len,
			   uint32_t iter,
			   uint32_t key_len, unsigned char *key)
{
	int ret;
	struct digest* d = digest_alloc("hmac(sha1)");

	ret = pkcs5_pbkdf2_hmac(d, pwd, pwd_len, salt, salt_len, iter,
				 key_len, key);

	digest_free(d);
	return ret;
}