1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6   @file xcbc_init.c
7   XCBC Support, start an XCBC state
8 */
9 
10 #ifdef LTC_XCBC
11 
12 /** Initialize XCBC-MAC state
13   @param xcbc    [out] XCBC state to initialize
14   @param cipher  Index of cipher to use
15   @param key     [in]  Secret key
16   @param keylen  Length of secret key in octets
17   Return CRYPT_OK on success
18 */
xcbc_init(xcbc_state * xcbc,int cipher,const unsigned char * key,unsigned long keylen)19 int xcbc_init(xcbc_state *xcbc, int cipher, const unsigned char *key, unsigned long keylen)
20 {
21    int            x, y, err;
22    symmetric_key *skey;
23    unsigned long  k1;
24 
25    LTC_ARGCHK(xcbc != NULL);
26    LTC_ARGCHK(key  != NULL);
27 
28    /* schedule the key */
29    if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
30       return err;
31    }
32 
33 #ifdef LTC_FAST
34    if (cipher_descriptor[cipher]->block_length % sizeof(LTC_FAST_TYPE)) {
35        return CRYPT_INVALID_ARG;
36    }
37 #endif
38 
39    skey = NULL;
40 
41    /* are we in pure XCBC mode with three keys? */
42    if (keylen & LTC_XCBC_PURE) {
43       keylen &= ~LTC_XCBC_PURE;
44 
45       if (keylen < 2UL*cipher_descriptor[cipher]->block_length) {
46          return CRYPT_INVALID_ARG;
47       }
48 
49       k1      = keylen - 2*cipher_descriptor[cipher]->block_length;
50       XMEMCPY(xcbc->K[0], key, k1);
51       XMEMCPY(xcbc->K[1], key+k1, cipher_descriptor[cipher]->block_length);
52       XMEMCPY(xcbc->K[2], key+k1 + cipher_descriptor[cipher]->block_length, cipher_descriptor[cipher]->block_length);
53    } else {
54       /* use the key expansion */
55       k1      = cipher_descriptor[cipher]->block_length;
56 
57       /* schedule the user key */
58       skey = XCALLOC(1, sizeof(*skey));
59       if (skey == NULL) {
60          return CRYPT_MEM;
61       }
62 
63       if ((err = cipher_descriptor[cipher]->setup(key, keylen, 0, skey)) != CRYPT_OK) {
64          goto done;
65       }
66 
67       /* make the three keys */
68       for (y = 0; y < 3; y++) {
69         for (x = 0; x < cipher_descriptor[cipher]->block_length; x++) {
70            xcbc->K[y][x] = y + 1;
71         }
72         cipher_descriptor[cipher]->ecb_encrypt(xcbc->K[y], xcbc->K[y], skey);
73       }
74    }
75 
76    /* setup K1 */
77    err = cipher_descriptor[cipher]->setup(xcbc->K[0], k1, 0, &xcbc->key);
78 
79    /* setup struct */
80    zeromem(xcbc->IV, cipher_descriptor[cipher]->block_length);
81    xcbc->blocksize = cipher_descriptor[cipher]->block_length;
82    xcbc->cipher    = cipher;
83    xcbc->buflen    = 0;
84 done:
85    cipher_descriptor[cipher]->done(skey);
86    if (skey != NULL) {
87 #ifdef LTC_CLEAN_STACK
88       zeromem(skey, sizeof(*skey));
89 #endif
90       XFREE(skey);
91    }
92    return err;
93 }
94 
95 #endif
96 
97