3 Miscellaneous functions used by the example programs.
5 Copyright (C) 2002, 2012 Niels Möller
7 This file is part of GNU Nettle.
9 GNU Nettle is free software: you can redistribute it and/or
10 modify it under the terms of either:
12 * the GNU Lesser General Public License as published by the Free
13 Software Foundation; either version 3 of the License, or (at your
14 option) any later version.
18 * the GNU General Public License as published by the Free
19 Software Foundation; either version 2 of the License, or (at your
20 option) any later version.
22 or both in parallel, as here.
24 GNU Nettle is distributed in the hope that it will be useful,
25 but WITHOUT ANY WARRANTY; without even the implied warranty of
26 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27 General Public License for more details.
29 You should have received copies of the GNU General Public License and
30 the GNU Lesser General Public License along with this program. If
31 not, see http://www.gnu.org/licenses/.
41 /* For errno and strerror */
47 #define RANDOM_DEVICE "/dev/urandom"
55 void *p = malloc(size);
58 fprintf(stderr, "Virtual memory exhausted.\n");
66 werror(const char *format, ...)
71 va_start(args, format);
72 vfprintf(stderr, format, args);
78 read_file(const char *name, unsigned max_size, char **contents)
84 f = fopen(name, "rb");
87 werror("Opening `%s' failed: %s\n", name, strerror(errno));
93 for (buffer = NULL, done = 0;; size *= 2)
97 if (max_size && size > max_size)
100 /* Space for terminating NUL */
101 p = realloc(buffer, size + 1);
113 done += fread(buffer + done, 1, size - done, f);
117 /* Short count means EOF or read error */
120 fprintf (stderr, "Reading `%s' failed: %s\n",
121 name, strerror(errno));
126 /* Treat empty file as error */
132 if (size == max_size)
138 /* NUL-terminate the data. */
146 write_string(FILE *f, unsigned size, const char *buffer)
148 size_t res = fwrite(buffer, 1, size, f);
154 write_file(const char *name, unsigned size, const char *buffer)
156 FILE *f = fopen(name, "wb");
162 res = write_string(f, size, buffer);
163 return fclose(f) == 0 && res;
167 simple_random(struct yarrow256_ctx *ctx, const char *name)
173 length = read_file(name, 0, &buffer);
175 length = read_file(RANDOM_DEVICE, 20, &buffer);
180 yarrow256_seed(ctx, length, buffer);
188 hash_file(const struct nettle_hash *hash, void *ctx, FILE *f)
192 char buffer[BUFSIZE];
193 size_t res = fread(buffer, 1, sizeof(buffer), f);
197 hash->update(ctx, res, buffer);