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 ocb_decrypt_verify_memory.c
13   OCB implementation, helper to decrypt block of memory, by Tom St Denis
14 */
15 #include "tomcrypt_private.h"
16 
17 #ifdef LTC_OCB_MODE
18 
19 /**
20    Decrypt and compare the tag with OCB.
21    @param cipher     The index of the cipher desired
22    @param key        The secret key
23    @param keylen     The length of the secret key (octets)
24    @param nonce      The session nonce (length of the block size of the block cipher)
25    @param ct         The ciphertext
26    @param ctlen      The length of the ciphertext (octets)
27    @param pt         [out] The plaintext
28    @param tag        The tag to compare against
29    @param taglen     The length of the tag (octets)
30    @param stat       [out] The result of the tag comparison (1==valid, 0==invalid)
31    @return CRYPT_OK if successful regardless of the tag comparison
32 */
ocb_decrypt_verify_memory(int cipher,const unsigned char * key,unsigned long keylen,const unsigned char * nonce,const unsigned char * ct,unsigned long ctlen,unsigned char * pt,const unsigned char * tag,unsigned long taglen,int * stat)33 int ocb_decrypt_verify_memory(int cipher,
34     const unsigned char *key,    unsigned long keylen,
35     const unsigned char *nonce,
36     const unsigned char *ct,     unsigned long ctlen,
37           unsigned char *pt,
38     const unsigned char *tag,    unsigned long taglen,
39           int           *stat)
40 {
41    int err;
42    ocb_state *ocb;
43 
44    LTC_ARGCHK(key    != NULL);
45    LTC_ARGCHK(nonce  != NULL);
46    LTC_ARGCHK(pt     != NULL);
47    LTC_ARGCHK(ct     != NULL);
48    LTC_ARGCHK(tag    != NULL);
49    LTC_ARGCHK(stat    != NULL);
50 
51    /* allocate memory */
52    ocb = XMALLOC(sizeof(ocb_state));
53    if (ocb == NULL) {
54       return CRYPT_MEM;
55    }
56 
57    if ((err = ocb_init(ocb, cipher, key, keylen, nonce)) != CRYPT_OK) {
58       goto LBL_ERR;
59    }
60 
61    while (ctlen > (unsigned long)ocb->block_len) {
62         if ((err = ocb_decrypt(ocb, ct, pt)) != CRYPT_OK) {
63             goto LBL_ERR;
64         }
65         ctlen   -= ocb->block_len;
66         pt      += ocb->block_len;
67         ct      += ocb->block_len;
68    }
69 
70    err = ocb_done_decrypt(ocb, ct, ctlen, pt, tag, taglen, stat);
71 LBL_ERR:
72 #ifdef LTC_CLEAN_STACK
73    zeromem(ocb, sizeof(ocb_state));
74 #endif
75 
76    XFREE(ocb);
77 
78    return err;
79 }
80 
81 #endif
82 
83 /* ref:         $Format:%D$ */
84 /* git commit:  $Format:%H$ */
85 /* commit time: $Format:%ai$ */
86