5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 * Copyright 2005 TRI-D Systems, Inc.
22 #include <openssl/hmac.h>
26 static const char rcsid[] = "$Id$";
30 * This implements HOTP per draft-mraihi-oath-hmac-otp-04.txt, for Digit = 6.
32 * The HOTP algorithm is:
33 * 1. HS = HMAC-SHA-1(K, C)
34 * Take the SHA-1 HMAC of the key (K) and counter (C).
36 * Take the "Dynamic Truncation" of the HMAC.
37 * 3. HOTP = StToNum(S) % 10^Digit
38 * Take the modulus of S as a bigendian integer.
40 * Returns 0 on success, -1 on failure. output is the ASCII HOTP on success.
43 otp_hotp_mac(const unsigned char counter[8], unsigned char output[7],
44 const unsigned char keyblock[OTP_MAX_KEY_LEN], size_t key_len,
45 const char *log_prefix)
47 unsigned char hmac[EVP_MAX_MD_SIZE]; /* >=20 */
49 uint32_t dbc; /* "dynamic binary code" from HOTP draft */
52 if (!HMAC(EVP_sha1(), keyblock, key_len, counter, 8, hmac, &hmac_len) ||
54 otp_log(OTP_LOG_ERR, "%s: %s: HMAC failed", log_prefix, __func__);
58 /* 2. the truncate step is unnecessarily complex */
62 offset = hmac[19] & 0x0F;
63 /* we can't just cast hmac[offset] because of alignment and endianness */
64 dbc = (hmac[offset] & 0x7F) << 24 |
65 hmac[offset + 1] << 16 |
66 hmac[offset + 2] << 8 |
70 /* 3. int conversion and modulus (as string) */
71 (void) sprintf(output, "%06lu", dbc % 1000000L);