ccm_init.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
  2. /* SPDX-License-Identifier: Unlicense */
  3. #include "tomcrypt_private.h"
  4. #ifdef LTC_CCM_MODE
  5. /**
  6. Initialize a CCM state
  7. @param ccm The CCM state to initialize
  8. @param cipher The index of the cipher to use
  9. @param key The secret key
  10. @param keylen The length of the secret key
  11. @param ptlen The length of the plain/cipher text that will be processed
  12. @param taglen The max length of the MAC tag
  13. @param aadlen The length of the AAD
  14. @return CRYPT_OK on success
  15. */
  16. int ccm_init(ccm_state *ccm, int cipher,
  17. const unsigned char *key, int keylen, int ptlen, int taglen, int aadlen)
  18. {
  19. int err;
  20. LTC_ARGCHK(ccm != NULL);
  21. LTC_ARGCHK(key != NULL);
  22. XMEMSET(ccm, 0, sizeof(ccm_state));
  23. /* check cipher input */
  24. if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
  25. return err;
  26. }
  27. if (cipher_descriptor[cipher].block_length != 16) {
  28. return CRYPT_INVALID_CIPHER;
  29. }
  30. /* make sure the taglen is valid */
  31. if (taglen < 4 || taglen > 16 || (taglen % 2) == 1) {
  32. return CRYPT_INVALID_ARG;
  33. }
  34. ccm->taglen = taglen;
  35. /* schedule key */
  36. if ((err = cipher_descriptor[cipher].setup(key, keylen, 0, &ccm->K)) != CRYPT_OK) {
  37. return err;
  38. }
  39. ccm->cipher = cipher;
  40. /* let's get the L value */
  41. ccm->ptlen = ptlen;
  42. ccm->L = 0;
  43. while (ptlen) {
  44. ++ccm->L;
  45. ptlen >>= 8;
  46. }
  47. if (ccm->L <= 1) {
  48. ccm->L = 2;
  49. }
  50. ccm->aadlen = aadlen;
  51. return CRYPT_OK;
  52. }
  53. #endif