forked from technion/libscrypt
/
crypto-scrypt-saltgen.c
71 lines (54 loc) · 1.24 KB
/
crypto-scrypt-saltgen.c
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
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#ifdef _WIN32
#pragma warning(push, 0)
#include <windows.h>
#pragma warning(pop)
#else
#ifndef S_SPLINT_S /* Including this here triggers a known bug in splint */
#include <unistd.h>
#endif
#define RNGDEV "/dev/urandom"
#endif
int libscrypt_salt_gen(uint8_t *salt, size_t len)
{
#ifdef _WIN32
HCRYPTPROV hProvider;
if (!CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
return -1;
}
BOOL res = CryptGenRandom(hProvider, (DWORD)len, salt);
CryptReleaseContext(hProvider, 0);
return res ? 0 : -1;
#else
unsigned char buf[len];
size_t data_read = 0;
int urandom = open(RNGDEV, O_RDONLY);
if (urandom < 0)
{
return -1;
}
while (data_read < len) {
ssize_t result = read(urandom, buf + data_read, len - data_read);
if (result < 0)
{
if (errno == EINTR || errno == EAGAIN) {
continue;
}
else {
(void)close(urandom);
return -1;
}
}
data_read += result;
}
/* Failures on close() shouldn't occur with O_RDONLY */
(void)close(urandom);
memcpy(salt, buf, len);
return 0;
#endif
}