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