radsecproxy-1.6.5.
[radsecproxy.git] / radsecproxy-hash.c
1 /*
2  * Copyright (C) 2011,2013 NORDUnet A/S
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12
13 #include "radsecproxy.h"
14 #include "fticks_hashmac.h"
15
16 void
17 usage()
18 {
19   fprintf(stderr,
20           "usage: radsecproxy-hash [-h] [-k key] [-t type]\n"
21 #if defined (READ_CONFIG)
22           "   -c configfile\tuse configuration from CONFIGFILE\n"
23 #endif
24           "   -h\t\t\tdisplay this help and exit\n"
25           "   -k key\t\tuse KEY for HMAC\n"
26           "   -t type\t\tprint digest of type TYPE [hash|hmac]\n");
27   exit(1);
28 }
29
30 #define MYNAME "radsecproxy-hash"
31
32 int
33 main(int argc, char *argv[])
34 {
35   int opt;
36 #if defined(READ_CONFIG)
37   char *config = NULL;
38 #endif
39   uint8_t buf[64+1];
40   char mac[80+1];
41   uint8_t *key = NULL;
42   enum { TYPE_HASH, TYPE_HMAC } type = TYPE_HASH;
43
44   while ((opt = getopt(argc, argv, "hk:t:")) != -1) {
45     switch (opt) {
46 #if defined(READ_CONFIG)
47     case 'c':
48       config = optarg;
49       break;
50 #endif
51     case 'h':
52       usage();
53     case 'k':
54       key = (uint8_t *) optarg;
55       break;
56     case 't':
57       if (strcmp(optarg, "hash") == 0)
58         type = TYPE_HASH;
59       else if (strcmp(optarg, "hmac") == 0)
60         type = TYPE_HMAC;
61       else
62         usage();
63       break;
64     default:
65       usage();
66     }
67   }
68
69   while (fgets(mac, sizeof(mac), stdin) != NULL) {
70     if (type == TYPE_HASH) {
71       if (fticks_hashmac((uint8_t *) mac, NULL, sizeof(buf), buf) != 0) {
72         fprintf(stderr, "%s: out of memory\n", MYNAME);
73         return 3;
74       }
75     }
76     else if (type == TYPE_HMAC) {
77       if (key == NULL) {
78         fprintf(stderr, "%s: generating HMAC requires a key, use `-k'\n",
79                 MYNAME);
80         return 2;
81       }
82       if (fticks_hashmac((uint8_t *) mac, key, sizeof(buf), buf) != 0) {
83         fprintf(stderr, "%s: out of memory\n", MYNAME);
84         return 3;
85       }
86     }
87     puts((const char *) buf);
88   }
89
90   return 0;
91 }