1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 #ifdef LTC_CCM_MODE
6 
7 /**
8   Add AAD to the CCM state
9   @param ccm       The CCM state
10   @param adata     The additional authentication data to add to the CCM state
11   @param adatalen  The length of the AAD data.
12   @return CRYPT_OK on success
13  */
ccm_add_aad(ccm_state * ccm,const unsigned char * adata,unsigned long adatalen)14 int ccm_add_aad(ccm_state *ccm,
15                 const unsigned char *adata,  unsigned long adatalen)
16 {
17    unsigned long y;
18    int            err;
19 
20    LTC_ARGCHK(ccm   != NULL);
21    LTC_ARGCHK(adata != NULL);
22 
23    if (ccm->aadlen < ccm->current_aadlen + adatalen) {
24       return CRYPT_INVALID_ARG;
25    }
26    ccm->current_aadlen += adatalen;
27 
28    /* now add the data */
29    for (y = 0; y < adatalen; y++) {
30       if (ccm->x == 16) {
31          /* full block so let's encrypt it */
32          if ((err = cipher_descriptor[ccm->cipher]->ecb_encrypt(ccm->PAD, ccm->PAD, &ccm->K)) != CRYPT_OK) {
33             return err;
34          }
35          ccm->x = 0;
36       }
37       ccm->PAD[ccm->x++] ^= adata[y];
38    }
39 
40    /* remainder? */
41    if (ccm->aadlen == ccm->current_aadlen) {
42       if (ccm->x != 0) {
43          if ((err = cipher_descriptor[ccm->cipher]->ecb_encrypt(ccm->PAD, ccm->PAD, &ccm->K)) != CRYPT_OK) {
44             return err;
45          }
46       }
47       ccm->x = 0;
48    }
49 
50    return CRYPT_OK;
51 }
52 
53 #endif
54