otpcli/cli.c

86 lines
1.8 KiB
C

/*
* otpcli - CLI utility for generating OTPs
*
* Written in 2020 by Lucas
*
* To the extent possible under law, the author(s) have dedicated all
* copyright and related and neighboring rights to this software to the
* public domain worldwide. This software is distributed without any
* warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication
* along with this software. If not, see
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "err.h"
#include "mystrtonum.h"
#include "otp.h"
extern const char *__progname;
static void
usage(void)
{
fprintf(stderr, "Usage: %s [-H counter] SECRET\n", __progname);
exit(1);
}
int
main(int argc, char *argv[])
{
const char *errstr;
uint64_t counter;
int32_t r;
int ch, do_hotp;
counter = 0;
do_hotp = 0;
while ((ch = getopt(argc, argv, "H:T:")) != -1) {
switch (ch) {
case 'H':
counter = mystrtonum(optarg, 0, LLONG_MAX, &errstr);
if (errstr != NULL)
errx(1, "counter is %s: %s", errstr, optarg);
do_hotp = 1;
break;
case 'T':
counter = mystrtonum(optarg, 0, LLONG_MAX, &errstr);
if (errstr != NULL)
errx(1, "counter is %s: %s", errstr, optarg);
do_hotp = 0;
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc != 1)
usage();
if (do_hotp) {
r = hotp(OTP_HMAC_SHA1, argv[0], strlen(argv[0]), counter, 6);
if (r == -1)
errx(1, "couldn't calculate HOTP");
printf("%" PRId32 "\n", r);
} else {
r = totp(OTP_HMAC_SHA1, argv[0], strlen(argv[0]), counter,
30, 8);
if (r == -1)
errx(1, "couldn't calculate TOTP");
printf("%" PRId32 "\n", r);
}
return 0;
}