aes-unwrap.c 1.6 KB

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