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 #ifdef LTC_CCM_MODE
13 
14 /**
15   Initialize a CCM state
16   @param ccm     The CCM state to initialize
17   @param cipher  The index of the cipher to use
18   @param key     The secret key
19   @param keylen  The length of the secret key
20   @param ptlen   The length of the plain/cipher text that will be processed
21   @param taglen  The max length of the MAC tag
22   @param aadlen  The length of the AAD
23 
24   @return CRYPT_OK on success
25  */
ccm_init(ccm_state * ccm,int cipher,const unsigned char * key,int keylen,int ptlen,int taglen,int aadlen)26 int ccm_init(ccm_state *ccm, int cipher,
27              const unsigned char *key, int keylen, int ptlen, int taglen, int aadlen)
28 {
29    int            err;
30 
31    LTC_ARGCHK(ccm    != NULL);
32    LTC_ARGCHK(key    != NULL);
33 
34    XMEMSET(ccm, 0, sizeof(ccm_state));
35 
36    /* check cipher input */
37    if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
38       return err;
39    }
40    if (cipher_descriptor[cipher]->block_length != 16) {
41       return CRYPT_INVALID_CIPHER;
42    }
43 
44    /* make sure the taglen is valid */
45    if (taglen < 4 || taglen > 16 || (taglen % 2) == 1) {
46       return CRYPT_INVALID_ARG;
47    }
48    ccm->taglen = taglen;
49 
50    /* schedule key */
51    if ((err = cipher_descriptor[cipher]->setup(key, keylen, 0, &ccm->K)) != CRYPT_OK) {
52       return err;
53    }
54    ccm->cipher = cipher;
55 
56    /* let's get the L value */
57    ccm->ptlen = ptlen;
58    ccm->L   = 0;
59    while (ptlen) {
60       ++ccm->L;
61       ptlen >>= 8;
62    }
63    if (ccm->L <= 1) {
64       ccm->L = 2;
65    }
66 
67    ccm->aadlen = aadlen;
68    return CRYPT_OK;
69 }
70 
71 #endif
72 
73 /* ref:         $Format:%D$ */
74 /* git commit:  $Format:%H$ */
75 /* commit time: $Format:%ai$ */
76