gcrypt RSA private key implementation
[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 /**
39 * Implementation of gcrypt_rng_t.get_bytes.
40 */
41 static void get_bytes(private_gcrypt_rng_t *this, size_t bytes,
42 u_int8_t *buffer)
43 {
44 switch (this->quality)
45 {
46 case RNG_WEAK:
47 gcry_create_nonce(buffer, bytes);
48 break;
49 case RNG_STRONG:
50 gcry_randomize(buffer, bytes, GCRY_STRONG_RANDOM);
51 break;
52 case RNG_TRUE:
53 gcry_randomize(buffer, bytes, GCRY_VERY_STRONG_RANDOM);
54 break;
55 }
56 }
57
58 /**
59 * Implementation of gcrypt_rng_t.allocate_bytes.
60 */
61 static void allocate_bytes(private_gcrypt_rng_t *this, size_t bytes,
62 chunk_t *chunk)
63 {
64 *chunk = chunk_alloc(bytes);
65 get_bytes(this, chunk->len, chunk->ptr);
66 }
67
68 /**
69 * Implementation of gcrypt_rng_t.destroy.
70 */
71 static void destroy(private_gcrypt_rng_t *this)
72 {
73 free(this);
74 }
75
76 /*
77 * Described in header.
78 */
79 gcrypt_rng_t *gcrypt_rng_create(rng_quality_t quality)
80 {
81 private_gcrypt_rng_t *this;
82
83 switch (quality)
84 {
85 case RNG_WEAK:
86 case RNG_STRONG:
87 case RNG_TRUE:
88 break;
89 default:
90 return NULL;
91 }
92
93 this = malloc_thing(private_gcrypt_rng_t);
94
95 this->public.rng.get_bytes = (void (*) (rng_t *, size_t, u_int8_t*)) get_bytes;
96 this->public.rng.allocate_bytes = (void (*) (rng_t *, size_t, chunk_t*)) allocate_bytes;
97 this->public.rng.destroy = (void (*) (rng_t *))destroy;
98
99 this->quality = quality;
100
101 return &this->public;
102 }
103