1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3
4 /**
5 @file ocb3_decrypt.c
6 OCB implementation, decrypt data, by Tom St Denis
7 */
8 #include "tomcrypt_private.h"
9
10 #ifdef LTC_OCB3_MODE
11
12 /**
13 Decrypt blocks of ciphertext with OCB
14 @param ocb The OCB state
15 @param ct The ciphertext (length multiple of the block size of the block cipher)
16 @param ctlen The length of the input (octets)
17 @param pt [out] The plaintext (length of ct)
18 @return CRYPT_OK if successful
19 */
ocb3_decrypt(ocb3_state * ocb,const unsigned char * ct,unsigned long ctlen,unsigned char * pt)20 int ocb3_decrypt(ocb3_state *ocb, const unsigned char *ct, unsigned long ctlen, unsigned char *pt)
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 (ctlen == 0) return CRYPT_OK; /* no data, nothing to do */
28 LTC_ARGCHK(ct != NULL);
29 LTC_ARGCHK(pt != 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 (ctlen % ocb->block_len) { /* ctlen has to bu multiple of block_len */
39 return CRYPT_INVALID_ARG;
40 }
41
42 full_blocks = ctlen/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[] = ct[] XOR ocb->Offset_current[] */
51 ocb3_int_xor_blocks(tmp, ct_b, ocb->Offset_current, ocb->block_len);
52
53 /* decrypt */
54 if ((err = cipher_descriptor[ocb->cipher]->ecb_decrypt(tmp, tmp, &ocb->key)) != CRYPT_OK) {
55 goto LBL_ERR;
56 }
57
58 /* pt[] = tmp[] XOR ocb->Offset_current[] */
59 ocb3_int_xor_blocks(pt_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