1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
6 * The library is free for all purposes without any express
14 Add nonce data to the CCM state
15 @param ccm The CCM state
16 @param nonce The nonce data to add
17 @param noncelen The length of the nonce
18 @return CRYPT_OK on success
20 int ccm_add_nonce(ccm_state *ccm,
21 const unsigned char *nonce, unsigned long noncelen)
23 unsigned long x, y, len;
26 LTC_ARGCHK(ccm != NULL);
27 LTC_ARGCHK(nonce != NULL);
29 /* increase L to match the nonce len */
30 ccm->noncelen = (noncelen > 13) ? 13 : noncelen;
31 if ((15 - ccm->noncelen) > ccm->L) {
32 ccm->L = 15 - ccm->noncelen;
35 /* decrease noncelen to match L */
36 if ((ccm->noncelen + ccm->L) > 15) {
37 ccm->noncelen = 15 - ccm->L;
40 /* form B_0 == flags | Nonce N | l(m) */
42 ccm->PAD[x++] = (unsigned char)(((ccm->aadlen > 0) ? (1<<6) : 0) |
43 (((ccm->taglen - 2)>>1)<<3) |
47 for (y = 0; y < (16 - (ccm->L + 1)); y++) {
48 ccm->PAD[x++] = nonce[y];
54 /* shift len so the upper bytes of len are the contents of the length */
55 for (y = ccm->L; y < 4; y++) {
59 /* store l(m) (only store 32-bits) */
60 for (y = 0; ccm->L > 4 && (ccm->L-y)>4; y++) {
63 for (; y < ccm->L; y++) {
64 ccm->PAD[x++] = (unsigned char)((len >> 24) & 255);
69 if ((err = cipher_descriptor[ccm->cipher].ecb_encrypt(ccm->PAD, ccm->PAD, &ccm->K)) != CRYPT_OK) {
75 if (ccm->aadlen > 0) {
77 if (ccm->aadlen < ((1UL<<16) - (1UL<<8))) {
78 ccm->PAD[ccm->x++] ^= (ccm->aadlen>>8) & 255;
79 ccm->PAD[ccm->x++] ^= ccm->aadlen & 255;
81 ccm->PAD[ccm->x++] ^= 0xFF;
82 ccm->PAD[ccm->x++] ^= 0xFE;
83 ccm->PAD[ccm->x++] ^= (ccm->aadlen>>24) & 255;
84 ccm->PAD[ccm->x++] ^= (ccm->aadlen>>16) & 255;
85 ccm->PAD[ccm->x++] ^= (ccm->aadlen>>8) & 255;
86 ccm->PAD[ccm->x++] ^= ccm->aadlen & 255;
90 /* setup the ctr counter */
94 ccm->ctr[x++] = (unsigned char)ccm->L-1;
97 for (y = 0; y < (16 - (ccm->L+1)); ++y) {
98 ccm->ctr[x++] = nonce[y];
111 /* ref: $Format:%D$ */
112 /* git commit: $Format:%H$ */
113 /* commit time: $Format:%ai$ */