1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 /**
5    @file ocb_decrypt.c
6    OCB implementation, decrypt data, by Tom St Denis
7 */
8 #include "tomcrypt_private.h"
9 
10 #ifdef LTC_OCB_MODE
11 
12 /**
13   Decrypt a block with OCB.
14   @param ocb    The OCB state
15   @param ct     The ciphertext (length of the block size of the block cipher)
16   @param pt     [out] The plaintext (length of ct)
17   @return CRYPT_OK if successful
18 */
ocb_decrypt(ocb_state * ocb,const unsigned char * ct,unsigned char * pt)19 int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt)
20 {
21    unsigned char Z[MAXBLOCKSIZE], tmp[MAXBLOCKSIZE];
22    int err, x;
23 
24    LTC_ARGCHK(ocb != NULL);
25    LTC_ARGCHK(pt  != NULL);
26    LTC_ARGCHK(ct  != NULL);
27 
28    /* check if valid cipher */
29    if ((err = cipher_is_valid(ocb->cipher)) != CRYPT_OK) {
30       return err;
31    }
32    LTC_ARGCHK(cipher_descriptor[ocb->cipher]->ecb_decrypt != NULL);
33 
34    /* check length */
35    if (ocb->block_len != cipher_descriptor[ocb->cipher]->block_length) {
36       return CRYPT_INVALID_ARG;
37    }
38 
39    /* Get Z[i] value */
40    ocb_shift_xor(ocb, Z);
41 
42    /* xor ct in, encrypt, xor Z out */
43    for (x = 0; x < ocb->block_len; x++) {
44        tmp[x] = ct[x] ^ Z[x];
45    }
46    if ((err = cipher_descriptor[ocb->cipher]->ecb_decrypt(tmp, pt, &ocb->key)) != CRYPT_OK) {
47       return err;
48    }
49    for (x = 0; x < ocb->block_len; x++) {
50        pt[x] ^= Z[x];
51    }
52 
53    /* compute checksum */
54    for (x = 0; x < ocb->block_len; x++) {
55        ocb->checksum[x] ^= pt[x];
56    }
57 
58 
59 #ifdef LTC_CLEAN_STACK
60    zeromem(Z, sizeof(Z));
61    zeromem(tmp, sizeof(tmp));
62 #endif
63    return CRYPT_OK;
64 }
65 
66 #endif
67 
68