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_decrypt.c
13    OCB implementation, decrypt data, by Tom St Denis
14 */
15 #include "tomcrypt_private.h"
16 
17 #ifdef LTC_OCB3_MODE
18 
19 /**
20    Decrypt blocks of ciphertext with OCB
21    @param ocb     The OCB state
22    @param ct      The ciphertext (length multiple of the block size of the block cipher)
23    @param ctlen   The length of the input (octets)
24    @param pt      [out] The plaintext (length of ct)
25    @return CRYPT_OK if successful
26 */
ocb3_decrypt(ocb3_state * ocb,const unsigned char * ct,unsigned long ctlen,unsigned char * pt)27 int ocb3_decrypt(ocb3_state *ocb, const unsigned char *ct, unsigned long ctlen, unsigned char *pt)
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 (ctlen == 0) return CRYPT_OK; /* no data, nothing to do */
35    LTC_ARGCHK(ct != NULL);
36    LTC_ARGCHK(pt != 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 (ctlen % ocb->block_len) { /* ctlen has to bu multiple of block_len */
46       return CRYPT_INVALID_ARG;
47    }
48 
49    full_blocks = ctlen/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[] = ct[] XOR ocb->Offset_current[] */
58      ocb3_int_xor_blocks(tmp, ct_b, ocb->Offset_current, ocb->block_len);
59 
60      /* decrypt */
61      if ((err = cipher_descriptor[ocb->cipher]->ecb_decrypt(tmp, tmp, &ocb->key)) != CRYPT_OK) {
62         goto LBL_ERR;
63      }
64 
65      /* pt[] = tmp[] XOR ocb->Offset_current[] */
66      ocb3_int_xor_blocks(pt_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