d29755de9c5ae547a9291d417af9a52d017f1890
[strongswan.git] / src / libstrongswan / plugins / gcrypt / gcrypt_rng.c
1 /*
2 * Copyright (C) 2009 Martin Willi
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "gcrypt_rng.h"
17
18 #include <gcrypt.h>
19
20 typedef struct private_gcrypt_rng_t private_gcrypt_rng_t;
21
22 /**
23 * Private data of an gcrypt_rng_t object.
24 */
25 struct private_gcrypt_rng_t {
26
27 /**
28 * Public gcrypt_rng_t interface.
29 */
30 gcrypt_rng_t public;
31
32 /**
33 * RNG quality of this instance
34 */
35 rng_quality_t quality;
36 };
37
38 METHOD(rng_t, get_bytes, void,
39 private_gcrypt_rng_t *this, size_t bytes, u_int8_t *buffer)
40 {
41 switch (this->quality)
42 {
43 case RNG_WEAK:
44 gcry_create_nonce(buffer, bytes);
45 break;
46 case RNG_STRONG:
47 gcry_randomize(buffer, bytes, GCRY_STRONG_RANDOM);
48 break;
49 case RNG_TRUE:
50 gcry_randomize(buffer, bytes, GCRY_VERY_STRONG_RANDOM);
51 break;
52 }
53 }
54
55 METHOD(rng_t, allocate_bytes, void,
56 private_gcrypt_rng_t *this, size_t bytes, chunk_t *chunk)
57 {
58 *chunk = chunk_alloc(bytes);
59 get_bytes(this, chunk->len, chunk->ptr);
60 }
61
62 METHOD(rng_t, destroy, void,
63 private_gcrypt_rng_t *this)
64 {
65 free(this);
66 }
67
68 /*
69 * Described in header.
70 */
71 gcrypt_rng_t *gcrypt_rng_create(rng_quality_t quality)
72 {
73 private_gcrypt_rng_t *this;
74
75 switch (quality)
76 {
77 case RNG_WEAK:
78 case RNG_STRONG:
79 case RNG_TRUE:
80 break;
81 default:
82 return NULL;
83 }
84
85 INIT(this,
86 .public = {
87 .rng = {
88 .get_bytes = _get_bytes,
89 .allocate_bytes = _allocate_bytes,
90 .destroy = _destroy,
91 },
92 },
93 .quality = quality,
94 );
95
96 return &this->public;
97 }
98