1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3
4 /**
5 @file ocb_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_OCB_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 pt The plaintext
19 @param ptlen The length of the plaintext (octets)
20 @param ct [out] The ciphertext
21 @param tag [out] The authentication tag
22 @param taglen [in/out] The max size and resulting size of the authentication tag
23 @return CRYPT_OK if successful
24 */
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)25 int ocb_encrypt_authenticate_memory(int cipher,
26 const unsigned char *key, unsigned long keylen,
27 const unsigned char *nonce,
28 const unsigned char *pt, unsigned long ptlen,
29 unsigned char *ct,
30 unsigned char *tag, unsigned long *taglen)
31 {
32 int err;
33 ocb_state *ocb;
34
35 LTC_ARGCHK(key != NULL);
36 LTC_ARGCHK(nonce != NULL);
37 LTC_ARGCHK(pt != NULL);
38 LTC_ARGCHK(ct != NULL);
39 LTC_ARGCHK(tag != NULL);
40 LTC_ARGCHK(taglen != NULL);
41
42 /* allocate ram */
43 ocb = XMALLOC(sizeof(ocb_state));
44 if (ocb == NULL) {
45 return CRYPT_MEM;
46 }
47
48 if ((err = ocb_init(ocb, cipher, key, keylen, nonce)) != CRYPT_OK) {
49 goto LBL_ERR;
50 }
51
52 while (ptlen > (unsigned long)ocb->block_len) {
53 if ((err = ocb_encrypt(ocb, pt, ct)) != CRYPT_OK) {
54 goto LBL_ERR;
55 }
56 ptlen -= ocb->block_len;
57 pt += ocb->block_len;
58 ct += ocb->block_len;
59 }
60
61 err = ocb_done_encrypt(ocb, pt, ptlen, ct, tag, taglen);
62 LBL_ERR:
63 #ifdef LTC_CLEAN_STACK
64 zeromem(ocb, sizeof(ocb_state));
65 #endif
66
67 XFREE(ocb);
68
69 return err;
70 }
71
72 #endif
73