File: rsa_common.c

package info (click to toggle)
openmohaa 0.82.1%2Bdfsg-1
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid
  • size: 34,192 kB
  • sloc: cpp: 315,720; ansic: 275,789; sh: 312; xml: 246; asm: 141; makefile: 7
file content (61 lines) | stat: -rw-r--r-- 1,415 bytes parent folder | download | duplicates (7)
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
#include "rsa_common.h"

void fail(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    fputs("\n", stderr);
    fflush(stderr);
    exit(1);
}

void write_file(const char *fname, const void *buf, const unsigned long len)
{
    FILE *io = fopen(fname, "wb");
    if (!io) {
        fail("Can't open '%s' for writing: %s", fname, strerror(errno));
    }

    if (fwrite(buf, len, 1, io) != 1) {
        fail("Couldn't write '%s': %s", fname, strerror(errno));
    }

    if (fclose(io) != 0) {
        fail("Couldn't flush '%s' to disk: %s", fname, strerror(errno));
    }
}

void read_file(const char *fname, void *buf, unsigned long *len)
{
    ssize_t br;
    FILE *io = fopen(fname, "rb");
    if (!io) {
        fail("Can't open '%s' for reading: %s", fname, strerror(errno));
    }

    br = fread(buf, 1, *len, io);
    if (ferror(io)) {
        fail("Couldn't read '%s': %s", fname, strerror(errno));
    } else if (!feof(io)) {
        fail("Buffer too small to read '%s'", fname);
    }
    fclose(io);

    *len = (unsigned long) br;
}

void read_rsakey(rsa_key *key, const char *fname)
{
    unsigned char buf[4096];
    unsigned long len = sizeof (buf);
    int rc;

    read_file(fname, buf, &len);

    if ((rc = rsa_import(buf, len, key)) != CRYPT_OK) {
        fail("rsa_import for '%s' failed: %s", fname, error_to_string(rc));
    }
}