1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 /**
5   @file ocb3_encrypt_authenticate_memory.c
6   OCB implementation, encrypt block of memory, by Tom St Denis
7 */
8 #include "tomcrypt_private.h"
9 
10 #ifdef LTC_OCB3_MODE
11 
12 /**
13    Encrypt and generate an authentication code for a buffer of memory
14    @param cipher     The index of the cipher desired
15    @param key        The secret key
16    @param keylen     The length of the secret key (octets)
17    @param nonce      The session nonce (length of the block ciphers block size)
18    @param noncelen   The length of the nonce (octets)
19    @param adata      The AAD - additional associated data
20    @param adatalen   The length of AAD (octets)
21    @param pt         The plaintext
22    @param ptlen      The length of the plaintext (octets)
23    @param ct         [out] The ciphertext
24    @param tag        [out] The authentication tag
25    @param taglen     [in/out] The max size and resulting size of the authentication tag
26    @return CRYPT_OK if successful
27 */
ocb3_encrypt_authenticate_memory(int cipher,const unsigned char * key,unsigned long keylen,const unsigned char * nonce,unsigned long noncelen,const unsigned char * adata,unsigned long adatalen,const unsigned char * pt,unsigned long ptlen,unsigned char * ct,unsigned char * tag,unsigned long * taglen)28 int ocb3_encrypt_authenticate_memory(int cipher,
29     const unsigned char *key,    unsigned long keylen,
30     const unsigned char *nonce,  unsigned long noncelen,
31     const unsigned char *adata,  unsigned long adatalen,
32     const unsigned char *pt,     unsigned long ptlen,
33           unsigned char *ct,
34           unsigned char *tag,    unsigned long *taglen)
35 {
36    int err;
37    ocb3_state *ocb;
38 
39    LTC_ARGCHK(taglen != NULL);
40 
41    /* allocate memory */
42    ocb = XMALLOC(sizeof(ocb3_state));
43    if (ocb == NULL) {
44       return CRYPT_MEM;
45    }
46 
47    if ((err = ocb3_init(ocb, cipher, key, keylen, nonce, noncelen, *taglen)) != CRYPT_OK) {
48       goto LBL_ERR;
49    }
50 
51    if (adata != NULL || adatalen != 0) {
52       if ((err = ocb3_add_aad(ocb, adata, adatalen)) != CRYPT_OK) {
53          goto LBL_ERR;
54       }
55    }
56 
57    if ((err = ocb3_encrypt_last(ocb, pt, ptlen, ct)) != CRYPT_OK) {
58       goto LBL_ERR;
59    }
60 
61    err = ocb3_done(ocb, tag, taglen);
62 
63 LBL_ERR:
64 #ifdef LTC_CLEAN_STACK
65    zeromem(ocb, sizeof(ocb3_state));
66 #endif
67 
68    XFREE(ocb);
69    return err;
70 }
71 
72 #endif
73