aes-ctr.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * AES-128/192/256 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_ctr_encrypt - AES-128/192/256 CTR mode encryption
  15. * @key: Key for encryption (key_len bytes)
  16. * @key_len: Length of the key (16, 24, or 32 bytes)
  17. * @nonce: Nonce for counter mode (16 bytes)
  18. * @data: Data to encrypt in-place
  19. * @data_len: Length of data in bytes
  20. * Returns: 0 on success, -1 on failure
  21. */
  22. int aes_ctr_encrypt(const u8 *key, size_t key_len, const u8 *nonce,
  23. u8 *data, size_t data_len)
  24. {
  25. void *ctx;
  26. size_t j, len, left = data_len;
  27. int i;
  28. u8 *pos = data;
  29. u8 counter[AES_BLOCK_SIZE], buf[AES_BLOCK_SIZE];
  30. ctx = aes_encrypt_init(key, key_len);
  31. if (ctx == NULL)
  32. return -1;
  33. os_memcpy(counter, nonce, AES_BLOCK_SIZE);
  34. while (left > 0) {
  35. aes_encrypt(ctx, counter, buf);
  36. len = (left < AES_BLOCK_SIZE) ? left : AES_BLOCK_SIZE;
  37. for (j = 0; j < len; j++)
  38. pos[j] ^= buf[j];
  39. pos += len;
  40. left -= len;
  41. for (i = AES_BLOCK_SIZE - 1; i >= 0; i--) {
  42. counter[i]++;
  43. if (counter[i])
  44. break;
  45. }
  46. }
  47. aes_encrypt_deinit(ctx);
  48. return 0;
  49. }
  50. /**
  51. * aes_128_ctr_encrypt - AES-128 CTR mode encryption
  52. * @key: Key for encryption (key_len bytes)
  53. * @nonce: Nonce for counter mode (16 bytes)
  54. * @data: Data to encrypt in-place
  55. * @data_len: Length of data in bytes
  56. * Returns: 0 on success, -1 on failure
  57. */
  58. int aes_128_ctr_encrypt(const u8 *key, const u8 *nonce,
  59. u8 *data, size_t data_len)
  60. {
  61. return aes_ctr_encrypt(key, 16, nonce, data, data_len);
  62. }