aes-wrap.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * AES Key Wrap Algorithm (128-bit KEK) (RFC3394)
  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_wrap - Wrap keys with AES Key Wrap Algorithm (128-bit KEK) (RFC3394)
  15. * @kek: 16-octet Key encryption key (KEK)
  16. * @n: Length of the plaintext key in 64-bit units; e.g., 2 = 128-bit = 16
  17. * bytes
  18. * @plain: Plaintext key to be wrapped, n * 64 bits
  19. * @cipher: Wrapped key, (n + 1) * 64 bits
  20. * Returns: 0 on success, -1 on failure
  21. */
  22. int aes_wrap(const u8 *kek, int n, const u8 *plain, u8 *cipher)
  23. {
  24. u8 *a, *r, b[16];
  25. int i, j;
  26. void *ctx;
  27. a = cipher;
  28. r = cipher + 8;
  29. /* 1) Initialize variables. */
  30. os_memset(a, 0xa6, 8);
  31. os_memcpy(r, plain, 8 * n);
  32. ctx = aes_encrypt_init(kek, 16);
  33. if (ctx == NULL)
  34. return -1;
  35. /* 2) Calculate intermediate values.
  36. * For j = 0 to 5
  37. * For i=1 to n
  38. * B = AES(K, A | R[i])
  39. * A = MSB(64, B) ^ t where t = (n*j)+i
  40. * R[i] = LSB(64, B)
  41. */
  42. for (j = 0; j <= 5; j++) {
  43. r = cipher + 8;
  44. for (i = 1; i <= n; i++) {
  45. os_memcpy(b, a, 8);
  46. os_memcpy(b + 8, r, 8);
  47. aes_encrypt(ctx, b, b);
  48. os_memcpy(a, b, 8);
  49. a[7] ^= n * j + i;
  50. os_memcpy(r, b + 8, 8);
  51. r += 8;
  52. }
  53. }
  54. aes_encrypt_deinit(ctx);
  55. /* 3) Output the results.
  56. *
  57. * These are already in @cipher due to the location of temporary
  58. * variables.
  59. */
  60. return 0;
  61. }