]> pd.if.org Git - zpackage/blob - libtomcrypt/src/encauth/ccm/ccm_process.c
commit files needed for zpm-fetchurl
[zpackage] / libtomcrypt / src / encauth / ccm / ccm_process.c
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2  *
3  * LibTomCrypt is a library that provides various cryptographic
4  * algorithms in a highly modular and flexible manner.
5  *
6  * The library is free for all purposes without any express
7  * guarantee it works.
8  */
9 #include "tomcrypt.h"
10
11 #ifdef LTC_CCM_MODE
12
13 /**
14   Process plaintext/ciphertext through CCM
15   @param ccm       The CCM state
16   @param pt        The plaintext
17   @param ptlen     The plaintext length (ciphertext length is the same)
18   @param ct        The ciphertext
19   @param direction Encrypt or Decrypt mode (CCM_ENCRYPT or CCM_DECRYPT)
20   @return CRYPT_OK on success
21  */
22 int ccm_process(ccm_state *ccm,
23                 unsigned char *pt,     unsigned long ptlen,
24                 unsigned char *ct,
25                 int direction)
26 {
27    unsigned char z, b;
28    unsigned long y;
29    int err;
30
31    LTC_ARGCHK(ccm != NULL);
32
33    /* Check aad has been correctly added */
34    if (ccm->aadlen != ccm->current_aadlen) {
35       return CRYPT_ERROR;
36    }
37
38    /* Check we do not process too much data */
39    if (ccm->ptlen < ccm->current_ptlen + ptlen) {
40       return CRYPT_ERROR;
41    }
42    ccm->current_ptlen += ptlen;
43
44    /* now handle the PT */
45    if (ptlen > 0) {
46       LTC_ARGCHK(pt != NULL);
47       LTC_ARGCHK(ct != NULL);
48
49       for (y = 0; y < ptlen; y++) {
50          /* increment the ctr? */
51          if (ccm->CTRlen == 16) {
52             for (z = 15; z > 15-ccm->L; z--) {
53                ccm->ctr[z] = (ccm->ctr[z] + 1) & 255;
54                if (ccm->ctr[z]) break;
55             }
56             if ((err = cipher_descriptor[ccm->cipher].ecb_encrypt(ccm->ctr, ccm->CTRPAD, &ccm->K)) != CRYPT_OK) {
57                return err;
58             }
59             ccm->CTRlen = 0;
60          }
61
62          /* if we encrypt we add the bytes to the MAC first */
63          if (direction == CCM_ENCRYPT) {
64             b     = pt[y];
65             ct[y] = b ^ ccm->CTRPAD[ccm->CTRlen++];
66          } else {
67             b     = ct[y] ^ ccm->CTRPAD[ccm->CTRlen++];
68             pt[y] = b;
69          }
70
71          if (ccm->x == 16) {
72             if ((err = cipher_descriptor[ccm->cipher].ecb_encrypt(ccm->PAD, ccm->PAD, &ccm->K)) != CRYPT_OK) {
73                return err;
74             }
75             ccm->x = 0;
76          }
77          ccm->PAD[ccm->x++] ^= b;
78       }
79    }
80
81    return CRYPT_OK;
82 }
83
84 #endif
85
86 /* ref:         $Format:%D$ */
87 /* git commit:  $Format:%H$ */
88 /* commit time: $Format:%ai$ */