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_encrypt_authenticate_memory.c
13   OCB implementation, encrypt block of memory, by Tom St Denis
14 */
15 #include "tomcrypt_private.h"
16 
17 #ifdef LTC_OCB_MODE
18 
19 /**
20    Encrypt and generate an authentication code for a buffer of memory
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 ciphers block size)
25    @param pt         The plaintext
26    @param ptlen      The length of the plaintext (octets)
27    @param ct         [out] The ciphertext
28    @param tag        [out] The authentication tag
29    @param taglen     [in/out] The max size and resulting size of the authentication tag
30    @return CRYPT_OK if successful
31 */
ocb_encrypt_authenticate_memory(int cipher,const unsigned char * key,unsigned long keylen,const unsigned char * nonce,const unsigned char * pt,unsigned long ptlen,unsigned char * ct,unsigned char * tag,unsigned long * taglen)32 int ocb_encrypt_authenticate_memory(int cipher,
33     const unsigned char *key,    unsigned long keylen,
34     const unsigned char *nonce,
35     const unsigned char *pt,     unsigned long ptlen,
36           unsigned char *ct,
37           unsigned char *tag,    unsigned long *taglen)
38 {
39    int err;
40    ocb_state *ocb;
41 
42    LTC_ARGCHK(key    != NULL);
43    LTC_ARGCHK(nonce  != NULL);
44    LTC_ARGCHK(pt     != NULL);
45    LTC_ARGCHK(ct     != NULL);
46    LTC_ARGCHK(tag    != NULL);
47    LTC_ARGCHK(taglen != NULL);
48 
49    /* allocate ram */
50    ocb = XMALLOC(sizeof(ocb_state));
51    if (ocb == NULL) {
52       return CRYPT_MEM;
53    }
54 
55    if ((err = ocb_init(ocb, cipher, key, keylen, nonce)) != CRYPT_OK) {
56       goto LBL_ERR;
57    }
58 
59    while (ptlen > (unsigned long)ocb->block_len) {
60         if ((err = ocb_encrypt(ocb, pt, ct)) != CRYPT_OK) {
61            goto LBL_ERR;
62         }
63         ptlen   -= ocb->block_len;
64         pt      += ocb->block_len;
65         ct      += ocb->block_len;
66    }
67 
68    err = ocb_done_encrypt(ocb, pt, ptlen, ct, tag, taglen);
69 LBL_ERR:
70 #ifdef LTC_CLEAN_STACK
71    zeromem(ocb, sizeof(ocb_state));
72 #endif
73 
74    XFREE(ocb);
75 
76    return err;
77 }
78 
79 #endif
80 
81 /* ref:         $Format:%D$ */
82 /* git commit:  $Format:%H$ */
83 /* commit time: $Format:%ai$ */
84