1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6   @file omac_done.c
7   OMAC1 support, terminate a stream, Tom St Denis
8 */
9 
10 #ifdef LTC_OMAC
11 
12 /**
13   Terminate an OMAC stream
14   @param omac   The OMAC state
15   @param out    [out] Destination for the authentication tag
16   @param outlen [in/out]  The max size and resulting size of the authentication tag
17   @return CRYPT_OK if successful
18 */
omac_done(omac_state * omac,unsigned char * out,unsigned long * outlen)19 int omac_done(omac_state *omac, unsigned char *out, unsigned long *outlen)
20 {
21    int       err, mode;
22    unsigned  x;
23 
24    LTC_ARGCHK(omac   != NULL);
25    LTC_ARGCHK(out    != NULL);
26    LTC_ARGCHK(outlen != NULL);
27    if ((err = cipher_is_valid(omac->cipher_idx)) != CRYPT_OK) {
28       return err;
29    }
30 
31    if ((omac->buflen > (int)sizeof(omac->block)) || (omac->buflen < 0) ||
32        (omac->blklen > (int)sizeof(omac->block)) || (omac->buflen > omac->blklen)) {
33       return CRYPT_INVALID_ARG;
34    }
35 
36    /* figure out mode */
37    if (omac->buflen != omac->blklen) {
38       /* add the 0x80 byte */
39       omac->block[omac->buflen++] = 0x80;
40 
41       /* pad with 0x00 */
42       while (omac->buflen < omac->blklen) {
43          omac->block[omac->buflen++] = 0x00;
44       }
45       mode = 1;
46    } else {
47       mode = 0;
48    }
49 
50    /* now xor prev + Lu[mode] */
51    for (x = 0; x < (unsigned)omac->blklen; x++) {
52        omac->block[x] ^= omac->prev[x] ^ omac->Lu[mode][x];
53    }
54 
55    /* encrypt it */
56    if ((err = cipher_descriptor[omac->cipher_idx]->ecb_encrypt(omac->block, omac->block, &omac->key)) != CRYPT_OK) {
57       return err;
58    }
59    cipher_descriptor[omac->cipher_idx]->done(&omac->key);
60 
61    /* output it */
62    for (x = 0; x < (unsigned)omac->blklen && x < *outlen; x++) {
63        out[x] = omac->block[x];
64    }
65    *outlen = x;
66 
67 #ifdef LTC_CLEAN_STACK
68    zeromem(omac, sizeof(*omac));
69 #endif
70    return CRYPT_OK;
71 }
72 
73 #endif
74 
75