1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6    @file lrw_start.c
7    LRW_MODE implementation, start mode, Tom St Denis
8 */
9 
10 #ifdef LTC_LRW_MODE
11 
12 /**
13   Initialize the LRW context
14   @param cipher        The cipher desired, must be a 128-bit block cipher
15   @param IV            The index value, must be 128-bits
16   @param key           The cipher key
17   @param keylen        The length of the cipher key in octets
18   @param tweak         The tweak value (second key), must be 128-bits
19   @param num_rounds    The number of rounds for the cipher (0 == default)
20   @param lrw           [out] The LRW state
21   @return CRYPT_OK on success.
22 */
lrw_start(int cipher,const unsigned char * IV,const unsigned char * key,int keylen,const unsigned char * tweak,int num_rounds,symmetric_LRW * lrw)23 int lrw_start(               int   cipher,
24               const unsigned char *IV,
25               const unsigned char *key,       int keylen,
26               const unsigned char *tweak,
27                              int  num_rounds,
28                    symmetric_LRW *lrw)
29 {
30    int           err;
31 #ifdef LTC_LRW_TABLES
32    unsigned char B[16];
33    int           x, y, z, t;
34 #endif
35 
36    LTC_ARGCHK(IV    != NULL);
37    LTC_ARGCHK(key   != NULL);
38    LTC_ARGCHK(tweak != NULL);
39    LTC_ARGCHK(lrw   != NULL);
40 
41 #ifdef LTC_FAST
42    if (16 % sizeof(LTC_FAST_TYPE)) {
43       return CRYPT_INVALID_ARG;
44    }
45 #endif
46 
47    /* is cipher valid? */
48    if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
49       return err;
50    }
51    if (cipher_descriptor[cipher]->block_length != 16) {
52       return CRYPT_INVALID_CIPHER;
53    }
54 
55    /* schedule key */
56    if ((err = cipher_descriptor[cipher]->setup(key, keylen, num_rounds, &lrw->key)) != CRYPT_OK) {
57       return err;
58    }
59    lrw->cipher = cipher;
60 
61    /* copy the IV and tweak */
62    XMEMCPY(lrw->tweak, tweak, 16);
63 
64 #ifdef LTC_LRW_TABLES
65    /* setup tables */
66    /* generate the first table as it has no shifting (from which we make the other tables) */
67    zeromem(B, 16);
68    for (y = 0; y < 256; y++) {
69         B[0] = y;
70         gcm_gf_mult(tweak, B, &lrw->PC[0][y][0]);
71    }
72 
73    /* now generate the rest of the tables based the previous table */
74    for (x = 1; x < 16; x++) {
75       for (y = 0; y < 256; y++) {
76          /* now shift it right by 8 bits */
77          t = lrw->PC[x-1][y][15];
78          for (z = 15; z > 0; z--) {
79              lrw->PC[x][y][z] = lrw->PC[x-1][y][z-1];
80          }
81          lrw->PC[x][y][0]  = gcm_shift_table[t<<1];
82          lrw->PC[x][y][1] ^= gcm_shift_table[(t<<1)+1];
83       }
84    }
85 #endif
86 
87    /* generate first pad */
88    return lrw_setiv(IV, 16, lrw);
89 }
90 
91 
92 #endif
93