aes-ctr.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * AES-128 CTR
  3. *
  4. * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
  5. *
  6. * This software may be distributed under the terms of the BSD license.
  7. * See README for more details.
  8. */
  9. #include "includes.h"
  10. #include "common.h"
  11. #include "aes.h"
  12. #include "aes_wrap.h"
  13. /**
  14. * aes_128_ctr_encrypt - AES-128 CTR mode encryption
  15. * @key: Key for encryption (16 bytes)
  16. * @nonce: Nonce for counter mode (16 bytes)
  17. * @data: Data to encrypt in-place
  18. * @data_len: Length of data in bytes
  19. * Returns: 0 on success, -1 on failure
  20. */
  21. int aes_128_ctr_encrypt(const u8 *key, const u8 *nonce,
  22. u8 *data, size_t data_len)
  23. {
  24. void *ctx;
  25. size_t j, len, left = data_len;
  26. int i;
  27. u8 *pos = data;
  28. u8 counter[AES_BLOCK_SIZE], buf[AES_BLOCK_SIZE];
  29. ctx = aes_encrypt_init(key, 16);
  30. if (ctx == NULL)
  31. return -1;
  32. os_memcpy(counter, nonce, AES_BLOCK_SIZE);
  33. while (left > 0) {
  34. aes_encrypt(ctx, counter, buf);
  35. len = (left < AES_BLOCK_SIZE) ? left : AES_BLOCK_SIZE;
  36. for (j = 0; j < len; j++)
  37. pos[j] ^= buf[j];
  38. pos += len;
  39. left -= len;
  40. for (i = AES_BLOCK_SIZE - 1; i >= 0; i--) {
  41. counter[i]++;
  42. if (counter[i])
  43. break;
  44. }
  45. }
  46. aes_encrypt_deinit(ctx);
  47. return 0;
  48. }