1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4
5 /**
6 @file lrw_process.c
7 LRW_MODE implementation, Encrypt/decrypt blocks, Tom St Denis
8 */
9
10 #ifdef LTC_LRW_MODE
11
12 /**
13 Process blocks with LRW, since decrypt/encrypt are largely the same they share this code.
14 @param pt The "input" data
15 @param ct [out] The "output" data
16 @param len The length of the input, must be a multiple of 128-bits (16 octets)
17 @param mode LRW_ENCRYPT or LRW_DECRYPT
18 @param lrw The LRW state
19 @return CRYPT_OK if successful
20 */
lrw_process(const unsigned char * pt,unsigned char * ct,unsigned long len,int mode,symmetric_LRW * lrw)21 int lrw_process(const unsigned char *pt, unsigned char *ct, unsigned long len, int mode, symmetric_LRW *lrw)
22 {
23 unsigned char prod[16];
24 int x, err;
25 #ifdef LTC_LRW_TABLES
26 int y;
27 #endif
28
29 LTC_ARGCHK(pt != NULL);
30 LTC_ARGCHK(ct != NULL);
31 LTC_ARGCHK(lrw != NULL);
32
33 if (len & 15) {
34 return CRYPT_INVALID_ARG;
35 }
36
37 while (len) {
38 /* copy pad */
39 XMEMCPY(prod, lrw->pad, 16);
40
41 /* increment IV */
42 for (x = 15; x >= 0; x--) {
43 lrw->IV[x] = (lrw->IV[x] + 1) & 255;
44 if (lrw->IV[x]) {
45 break;
46 }
47 }
48
49 /* update pad */
50 #ifdef LTC_LRW_TABLES
51 /* for each byte changed we undo it's affect on the pad then add the new product */
52 for (; x < 16; x++) {
53 #ifdef LTC_FAST
54 for (y = 0; y < 16; y += sizeof(LTC_FAST_TYPE)) {
55 *(LTC_FAST_TYPE_PTR_CAST(lrw->pad + y)) ^= *(LTC_FAST_TYPE_PTR_CAST(&lrw->PC[x][lrw->IV[x]][y])) ^ *(LTC_FAST_TYPE_PTR_CAST(&lrw->PC[x][(lrw->IV[x]-1)&255][y]));
56 }
57 #else
58 for (y = 0; y < 16; y++) {
59 lrw->pad[y] ^= lrw->PC[x][lrw->IV[x]][y] ^ lrw->PC[x][(lrw->IV[x]-1)&255][y];
60 }
61 #endif
62 }
63 #else
64 gcm_gf_mult(lrw->tweak, lrw->IV, lrw->pad);
65 #endif
66
67 /* xor prod */
68 #ifdef LTC_FAST
69 for (x = 0; x < 16; x += sizeof(LTC_FAST_TYPE)) {
70 *(LTC_FAST_TYPE_PTR_CAST(ct + x)) = *(LTC_FAST_TYPE_PTR_CAST(pt + x)) ^ *(LTC_FAST_TYPE_PTR_CAST(prod + x));
71 }
72 #else
73 for (x = 0; x < 16; x++) {
74 ct[x] = pt[x] ^ prod[x];
75 }
76 #endif
77
78 /* send through cipher */
79 if (mode == LRW_ENCRYPT) {
80 if ((err = cipher_descriptor[lrw->cipher]->ecb_encrypt(ct, ct, &lrw->key)) != CRYPT_OK) {
81 return err;
82 }
83 } else {
84 if ((err = cipher_descriptor[lrw->cipher]->ecb_decrypt(ct, ct, &lrw->key)) != CRYPT_OK) {
85 return err;
86 }
87 }
88
89 /* xor prod */
90 #ifdef LTC_FAST
91 for (x = 0; x < 16; x += sizeof(LTC_FAST_TYPE)) {
92 *(LTC_FAST_TYPE_PTR_CAST(ct + x)) = *(LTC_FAST_TYPE_PTR_CAST(ct + x)) ^ *(LTC_FAST_TYPE_PTR_CAST(prod + x));
93 }
94 #else
95 for (x = 0; x < 16; x++) {
96 ct[x] = ct[x] ^ prod[x];
97 }
98 #endif
99
100 /* move to next */
101 pt += 16;
102 ct += 16;
103 len -= 16;
104 }
105
106 return CRYPT_OK;
107 }
108
109 #endif
110