• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
2
3#ifndef _UECC_PLATFORM_SPECIFIC_H_
4#define _UECC_PLATFORM_SPECIFIC_H_
5
6#include "types.h"
7
8#if (defined(_WIN32) || defined(_WIN64))
9/* Windows */
10
11// use pragma syntax to prevent tweaking the linker script for getting CryptXYZ function
12#pragma comment(lib, "crypt32.lib")
13#pragma comment(lib, "advapi32.lib")
14
15#define WIN32_LEAN_AND_MEAN
16#include <windows.h>
17#include <wincrypt.h>
18
19static int default_RNG(uint8_t *dest, unsigned size) {
20    HCRYPTPROV prov;
21    if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
22        return 0;
23    }
24
25    CryptGenRandom(prov, size, (BYTE *)dest);
26    CryptReleaseContext(prov, 0);
27    return 1;
28}
29#define default_RNG_defined 1
30
31#elif defined(unix) || defined(__linux__) || defined(__unix__) || defined(__unix) || \
32    (defined(__APPLE__) && defined(__MACH__)) || defined(uECC_POSIX)
33
34/* Some POSIX-like system with /dev/urandom or /dev/random. */
35#include <sys/types.h>
36#include <fcntl.h>
37#include <unistd.h>
38
39#ifndef O_CLOEXEC
40    #define O_CLOEXEC 0
41#endif
42
43static int default_RNG(uint8_t *dest, unsigned size) {
44    int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
45    if (fd == -1) {
46        fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
47        if (fd == -1) {
48            return 0;
49        }
50    }
51
52    char *ptr = (char *)dest;
53    size_t left = size;
54    while (left > 0) {
55        ssize_t bytes_read = read(fd, ptr, left);
56        if (bytes_read <= 0) { // read failed
57            close(fd);
58            return 0;
59        }
60        left -= bytes_read;
61        ptr += bytes_read;
62    }
63
64    close(fd);
65    return 1;
66}
67#define default_RNG_defined 1
68
69#endif /* platform */
70
71#endif /* _UECC_PLATFORM_SPECIFIC_H_ */
72