Path: blob/master/libs/tomcrypt/src/encauth/ccm/ccm_add_nonce.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/**13Add nonce data to the CCM state14@param ccm The CCM state15@param nonce The nonce data to add16@param noncelen The length of the nonce17@return CRYPT_OK on success18*/19int ccm_add_nonce(ccm_state *ccm,20const unsigned char *nonce, unsigned long noncelen)21{22unsigned long x, y, len;23int err;2425LTC_ARGCHK(ccm != NULL);26LTC_ARGCHK(nonce != NULL);2728/* increase L to match the nonce len */29ccm->noncelen = (noncelen > 13) ? 13 : noncelen;30if ((15 - ccm->noncelen) > ccm->L) {31ccm->L = 15 - ccm->noncelen;32}3334/* decrease noncelen to match L */35if ((ccm->noncelen + ccm->L) > 15) {36ccm->noncelen = 15 - ccm->L;37}3839/* form B_0 == flags | Nonce N | l(m) */40x = 0;41ccm->PAD[x++] = (unsigned char)(((ccm->aadlen > 0) ? (1<<6) : 0) |42(((ccm->taglen - 2)>>1)<<3) |43(ccm->L-1));4445/* nonce */46for (y = 0; y < (16 - (ccm->L + 1)); y++) {47ccm->PAD[x++] = nonce[y];48}4950/* store len */51len = ccm->ptlen;5253/* shift len so the upper bytes of len are the contents of the length */54for (y = ccm->L; y < 4; y++) {55len <<= 8;56}5758/* store l(m) (only store 32-bits) */59for (y = 0; ccm->L > 4 && (ccm->L-y)>4; y++) {60ccm->PAD[x++] = 0;61}62for (; y < ccm->L; y++) {63ccm->PAD[x++] = (unsigned char)((len >> 24) & 255);64len <<= 8;65}6667/* encrypt PAD */68if ((err = cipher_descriptor[ccm->cipher].ecb_encrypt(ccm->PAD, ccm->PAD, &ccm->K)) != CRYPT_OK) {69return err;70}7172/* handle header */73ccm->x = 0;74if (ccm->aadlen > 0) {75/* store length */76if (ccm->aadlen < ((1UL<<16) - (1UL<<8))) {77ccm->PAD[ccm->x++] ^= (ccm->aadlen>>8) & 255;78ccm->PAD[ccm->x++] ^= ccm->aadlen & 255;79} else {80ccm->PAD[ccm->x++] ^= 0xFF;81ccm->PAD[ccm->x++] ^= 0xFE;82ccm->PAD[ccm->x++] ^= (ccm->aadlen>>24) & 255;83ccm->PAD[ccm->x++] ^= (ccm->aadlen>>16) & 255;84ccm->PAD[ccm->x++] ^= (ccm->aadlen>>8) & 255;85ccm->PAD[ccm->x++] ^= ccm->aadlen & 255;86}87}8889/* setup the ctr counter */90x = 0;9192/* flags */93ccm->ctr[x++] = (unsigned char)ccm->L-1;9495/* nonce */96for (y = 0; y < (16 - (ccm->L+1)); ++y) {97ccm->ctr[x++] = nonce[y];98}99/* offset */100while (x < 16) {101ccm->ctr[x++] = 0;102}103104ccm->CTRlen = 16;105return CRYPT_OK;106}107108#endif109110111