Path: blob/master/libs/tomcrypt/src/encauth/ccm/ccm_process.c
5972 views
/* LibTomCrypt, modular cryptographic library -- Tom St Denis1*2* LibTomCrypt is a library that provides various cryptographic3* algorithms in a highly modular and flexible manner.4*5* The library is free for all purposes without any express6* guarantee it works.7*/8#include "tomcrypt.h"910#ifdef LTC_CCM_MODE1112/**13Process plaintext/ciphertext through CCM14@param ccm The CCM state15@param pt The plaintext16@param ptlen The plaintext length (ciphertext length is the same)17@param ct The ciphertext18@param direction Encrypt or Decrypt mode (CCM_ENCRYPT or CCM_DECRYPT)19@return CRYPT_OK on success20*/21int ccm_process(ccm_state *ccm,22unsigned char *pt, unsigned long ptlen,23unsigned char *ct,24int direction)25{26unsigned char z, b;27unsigned long y;28int err;2930LTC_ARGCHK(ccm != NULL);3132/* Check aad has been correctly added */33if (ccm->aadlen != ccm->current_aadlen) {34return CRYPT_ERROR;35}3637/* Check we do not process too much data */38if (ccm->ptlen < ccm->current_ptlen + ptlen) {39return CRYPT_ERROR;40}41ccm->current_ptlen += ptlen;4243/* now handle the PT */44if (ptlen > 0) {45LTC_ARGCHK(pt != NULL);46LTC_ARGCHK(ct != NULL);4748for (y = 0; y < ptlen; y++) {49/* increment the ctr? */50if (ccm->CTRlen == 16) {51for (z = 15; z > 15-ccm->L; z--) {52ccm->ctr[z] = (ccm->ctr[z] + 1) & 255;53if (ccm->ctr[z]) break;54}55if ((err = cipher_descriptor[ccm->cipher].ecb_encrypt(ccm->ctr, ccm->CTRPAD, &ccm->K)) != CRYPT_OK) {56return err;57}58ccm->CTRlen = 0;59}6061/* if we encrypt we add the bytes to the MAC first */62if (direction == CCM_ENCRYPT) {63b = pt[y];64ct[y] = b ^ ccm->CTRPAD[ccm->CTRlen++];65} else {66b = ct[y] ^ ccm->CTRPAD[ccm->CTRlen++];67pt[y] = b;68}6970if (ccm->x == 16) {71if ((err = cipher_descriptor[ccm->cipher].ecb_encrypt(ccm->PAD, ccm->PAD, &ccm->K)) != CRYPT_OK) {72return err;73}74ccm->x = 0;75}76ccm->PAD[ccm->x++] ^= b;77}78}7980return CRYPT_OK;81}8283#endif848586