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