aes-wrap.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * AES Key Wrap Algorithm (128-bit KEK) (RFC3394)
  3. *
  4. * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License version 2 as
  8. * published by the Free Software Foundation.
  9. *
  10. * Alternatively, this software may be distributed under the terms of BSD
  11. * license.
  12. *
  13. * See README and COPYING for more details.
  14. */
  15. #include "includes.h"
  16. #include "common.h"
  17. #include "aes.h"
  18. #include "aes_wrap.h"
  19. /**
  20. * aes_wrap - Wrap keys with AES Key Wrap Algorithm (128-bit KEK) (RFC3394)
  21. * @kek: 16-octet Key encryption key (KEK)
  22. * @n: Length of the plaintext key in 64-bit units; e.g., 2 = 128-bit = 16
  23. * bytes
  24. * @plain: Plaintext key to be wrapped, n * 64 bits
  25. * @cipher: Wrapped key, (n + 1) * 64 bits
  26. * Returns: 0 on success, -1 on failure
  27. */
  28. int aes_wrap(const u8 *kek, int n, const u8 *plain, u8 *cipher)
  29. {
  30. u8 *a, *r, b[16];
  31. int i, j;
  32. void *ctx;
  33. a = cipher;
  34. r = cipher + 8;
  35. /* 1) Initialize variables. */
  36. os_memset(a, 0xa6, 8);
  37. os_memcpy(r, plain, 8 * n);
  38. ctx = aes_encrypt_init(kek, 16);
  39. if (ctx == NULL)
  40. return -1;
  41. /* 2) Calculate intermediate values.
  42. * For j = 0 to 5
  43. * For i=1 to n
  44. * B = AES(K, A | R[i])
  45. * A = MSB(64, B) ^ t where t = (n*j)+i
  46. * R[i] = LSB(64, B)
  47. */
  48. for (j = 0; j <= 5; j++) {
  49. r = cipher + 8;
  50. for (i = 1; i <= n; i++) {
  51. os_memcpy(b, a, 8);
  52. os_memcpy(b + 8, r, 8);
  53. aes_encrypt(ctx, b, b);
  54. os_memcpy(a, b, 8);
  55. a[7] ^= n * j + i;
  56. os_memcpy(r, b + 8, 8);
  57. r += 8;
  58. }
  59. }
  60. aes_encrypt_deinit(ctx);
  61. /* 3) Output the results.
  62. *
  63. * These are already in @cipher due to the location of temporary
  64. * variables.
  65. */
  66. return 0;
  67. }