1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 /**
5    @file ocb3_encrypt.c
6    OCB implementation, encrypt data, by Tom St Denis
7 */
8 #include "tomcrypt_private.h"
9 
10 #ifdef LTC_OCB3_MODE
11 
12 /**
13    Encrypt blocks of data with OCB
14    @param ocb     The OCB state
15    @param pt      The plaintext (length multiple of the block size of the block cipher)
16    @param ptlen   The length of the input (octets)
17    @param ct      [out] The ciphertext (same size as the pt)
18    @return CRYPT_OK if successful
19 */
ocb3_encrypt(ocb3_state * ocb,const unsigned char * pt,unsigned long ptlen,unsigned char * ct)20 int ocb3_encrypt(ocb3_state *ocb, const unsigned char *pt, unsigned long ptlen, unsigned char *ct)
21 {
22    unsigned char tmp[MAXBLOCKSIZE];
23    int err, i, full_blocks;
24    unsigned char *pt_b, *ct_b;
25 
26    LTC_ARGCHK(ocb != NULL);
27    if (ptlen == 0) return CRYPT_OK; /* no data, nothing to do */
28    LTC_ARGCHK(pt != NULL);
29    LTC_ARGCHK(ct != NULL);
30 
31    if ((err = cipher_is_valid(ocb->cipher)) != CRYPT_OK) {
32       return err;
33    }
34    if (ocb->block_len != cipher_descriptor[ocb->cipher]->block_length) {
35       return CRYPT_INVALID_ARG;
36    }
37 
38    if (ptlen % ocb->block_len) { /* ptlen has to bu multiple of block_len */
39       return CRYPT_INVALID_ARG;
40    }
41 
42    full_blocks = ptlen/ocb->block_len;
43    for(i=0; i<full_blocks; i++) {
44      pt_b = (unsigned char *)pt+i*ocb->block_len;
45      ct_b = (unsigned char *)ct+i*ocb->block_len;
46 
47      /* ocb->Offset_current[] = ocb->Offset_current[] ^ Offset_{ntz(block_index)} */
48      ocb3_int_xor_blocks(ocb->Offset_current, ocb->Offset_current, ocb->L_[ocb3_int_ntz(ocb->block_index)], ocb->block_len);
49 
50      /* tmp[] = pt[] XOR ocb->Offset_current[] */
51      ocb3_int_xor_blocks(tmp, pt_b, ocb->Offset_current, ocb->block_len);
52 
53      /* encrypt */
54      if ((err = cipher_descriptor[ocb->cipher]->ecb_encrypt(tmp, tmp, &ocb->key)) != CRYPT_OK) {
55         goto LBL_ERR;
56      }
57 
58      /* ct[] = tmp[] XOR ocb->Offset_current[] */
59      ocb3_int_xor_blocks(ct_b, tmp, ocb->Offset_current, ocb->block_len);
60 
61      /* ocb->checksum[] = ocb->checksum[] XOR pt[] */
62      ocb3_int_xor_blocks(ocb->checksum, ocb->checksum, pt_b, ocb->block_len);
63 
64      ocb->block_index++;
65    }
66 
67    err = CRYPT_OK;
68 
69 LBL_ERR:
70 #ifdef LTC_CLEAN_STACK
71    zeromem(tmp, sizeof(tmp));
72 #endif
73    return err;
74 }
75 
76 #endif
77