summaryrefslogtreecommitdiffhomepage
path: root/src/prng_mbed.c
blob: 7a3a6d1b812941ebb5530fcd416c72fb76d149e2 (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
/**
 * Copyright (C) 2021 Mikael Magnusson <mikma@user.sourceforge.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License v2 as published by
 * the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */

#include "prng.h"

#include <stddef.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include <mbedtls/md.h>


/* PRNG using SHA1 from mbedtls. */
struct prng_context_s
{
	mbedtls_md_context_t md;
};


prng_context_t *prng_alloc()
{
	prng_context_t *ctx = calloc(1, sizeof(prng_context_t));
	mbedtls_md_init(&ctx->md);
	return ctx;
}

void prng_setup(prng_context_t *ctx)
{
	mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
	mbedtls_md_setup(&ctx->md, mbedtls_md_info_from_type(md_type), 0);
}

void prng_starts(prng_context_t *ctx)
{
	mbedtls_md_starts(&ctx->md);
}

void prng_update(prng_context_t *ctx, const uint8_t *input, size_t ilen)
{
	mbedtls_md_update(&ctx->md, (const unsigned char *) input, ilen);
}

void prng_finish(prng_context_t *ctx, uint8_t *output, uint8_t *output2)
{
	uint8_t tmp[160];
	mbedtls_md_finish(&ctx->md, tmp);
	memcpy(output, tmp, 8);
	if (output2)
		memcpy(output2, tmp + 8, 8);
}

#if 0
void prng_free()
{
	mbedtls_md_free(ctx);
}
#endif