aes-cbc.c 1.9 KB

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