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