aboutsummaryrefslogtreecommitdiff
path: root/randgen_win32.c
blob: d0b4123f24350dd06611df1db32631c5ab8e83eb (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
#include "randgen.h"

#include <windows.h>
#include <wincrypt.h>

#include <stdio.h>
#include <assert.h>

struct randgen *randgen_open(const char *device)
{
    HCRYPTPROV prov;

    (void) device;

    if (!CryptAcquireContextW(&prov, 0, 0, PROV_RSA_FULL,
        CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
    {
        fprintf(stderr, "failed to open random generator: CryptAcquireContextW failed\n");
        return NULL;
    }

    return (struct randgen *) prov;
}

int randgen_close(struct randgen *randgen)
{
    assert(randgen != NULL);
    CryptReleaseContext((HCRYPTPROV) randgen, 0);
    return 0;
}

int randgen_generate(struct randgen *randgen, void *buf, size_t size)
{
    assert(randgen != NULL);
    assert(buf != NULL);
    assert(size > 0);

    if (!CryptGenRandom((HCRYPTPROV) randgen, size, buf))
        return -1;

    return 0;
}