aes-cbc.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * AES-128 CBC
  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_cbc_encrypt - AES-128 CBC encryption
  15. * @key: Encryption key
  16. * @iv: Encryption IV for CBC mode (16 bytes)
  17. * @data: Data to encrypt in-place
  18. * @data_len: Length of data in bytes (must be divisible by 16)
  19. * Returns: 0 on success, -1 on failure
  20. */
  21. int aes_128_cbc_encrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
  22. {
  23. void *ctx;
  24. u8 cbc[AES_BLOCK_SIZE];
  25. u8 *pos = data;
  26. int i, j, blocks;
  27. ctx = aes_encrypt_init(key, 16);
  28. if (ctx == NULL)
  29. return -1;
  30. os_memcpy(cbc, iv, AES_BLOCK_SIZE);
  31. blocks = data_len / AES_BLOCK_SIZE;
  32. for (i = 0; i < blocks; i++) {
  33. for (j = 0; j < AES_BLOCK_SIZE; j++)
  34. cbc[j] ^= pos[j];
  35. aes_encrypt(ctx, cbc, cbc);
  36. os_memcpy(pos, cbc, AES_BLOCK_SIZE);
  37. pos += AES_BLOCK_SIZE;
  38. }
  39. aes_encrypt_deinit(ctx);
  40. return 0;
  41. }
  42. /**
  43. * aes_128_cbc_decrypt - AES-128 CBC decryption
  44. * @key: Decryption key
  45. * @iv: Decryption IV for CBC mode (16 bytes)
  46. * @data: Data to decrypt in-place
  47. * @data_len: Length of data in bytes (must be divisible by 16)
  48. * Returns: 0 on success, -1 on failure
  49. */
  50. int aes_128_cbc_decrypt(const u8 *key, const u8 *iv, u8 *data, size_t data_len)
  51. {
  52. void *ctx;
  53. u8 cbc[AES_BLOCK_SIZE], tmp[AES_BLOCK_SIZE];
  54. u8 *pos = data;
  55. int i, j, blocks;
  56. ctx = aes_decrypt_init(key, 16);
  57. if (ctx == NULL)
  58. return -1;
  59. os_memcpy(cbc, iv, AES_BLOCK_SIZE);
  60. blocks = data_len / AES_BLOCK_SIZE;
  61. for (i = 0; i < blocks; i++) {
  62. os_memcpy(tmp, pos, AES_BLOCK_SIZE);
  63. aes_decrypt(ctx, pos, pos);
  64. for (j = 0; j < AES_BLOCK_SIZE; j++)
  65. pos[j] ^= cbc[j];
  66. os_memcpy(cbc, tmp, AES_BLOCK_SIZE);
  67. pos += AES_BLOCK_SIZE;
  68. }
  69. aes_decrypt_deinit(ctx);
  70. return 0;
  71. }