aes_gmac.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * AES-GMAC for IEEE 802.11 BIP-GMAC-128 and BIP-GMAC-256
  3. * Copyright 2015, Qualcomm Atheros, Inc.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2 as
  7. * published by the Free Software Foundation.
  8. */
  9. #include <linux/kernel.h>
  10. #include <linux/types.h>
  11. #include <linux/err.h>
  12. #include <crypto/aead.h>
  13. #include <crypto/aes.h>
  14. #include <net/mac80211.h>
  15. #include "key.h"
  16. #include "aes_gmac.h"
  17. #define GMAC_MIC_LEN 16
  18. #define GMAC_NONCE_LEN 12
  19. #define AAD_LEN 20
  20. int ieee80211_aes_gmac(struct crypto_aead *tfm, const u8 *aad, u8 *nonce,
  21. const u8 *data, size_t data_len, u8 *mic)
  22. {
  23. struct scatterlist sg[4];
  24. char aead_req_data[sizeof(struct aead_request) +
  25. crypto_aead_reqsize(tfm)]
  26. __aligned(__alignof__(struct aead_request));
  27. struct aead_request *aead_req = (void *)aead_req_data;
  28. u8 zero[GMAC_MIC_LEN], iv[AES_BLOCK_SIZE];
  29. if (data_len < GMAC_MIC_LEN)
  30. return -EINVAL;
  31. memset(aead_req, 0, sizeof(aead_req_data));
  32. memset(zero, 0, GMAC_MIC_LEN);
  33. sg_init_table(sg, 4);
  34. sg_set_buf(&sg[0], aad, AAD_LEN);
  35. sg_set_buf(&sg[1], data, data_len - GMAC_MIC_LEN);
  36. sg_set_buf(&sg[2], zero, GMAC_MIC_LEN);
  37. sg_set_buf(&sg[3], mic, GMAC_MIC_LEN);
  38. memcpy(iv, nonce, GMAC_NONCE_LEN);
  39. memset(iv + GMAC_NONCE_LEN, 0, sizeof(iv) - GMAC_NONCE_LEN);
  40. iv[AES_BLOCK_SIZE - 1] = 0x01;
  41. aead_request_set_tfm(aead_req, tfm);
  42. aead_request_set_crypt(aead_req, sg, sg, 0, iv);
  43. aead_request_set_ad(aead_req, AAD_LEN + data_len);
  44. crypto_aead_encrypt(aead_req);
  45. return 0;
  46. }
  47. struct crypto_aead *ieee80211_aes_gmac_key_setup(const u8 key[],
  48. size_t key_len)
  49. {
  50. struct crypto_aead *tfm;
  51. int err;
  52. tfm = crypto_alloc_aead("gcm(aes)", 0, CRYPTO_ALG_ASYNC);
  53. if (IS_ERR(tfm))
  54. return tfm;
  55. err = crypto_aead_setkey(tfm, key, key_len);
  56. if (!err)
  57. err = crypto_aead_setauthsize(tfm, GMAC_MIC_LEN);
  58. if (!err)
  59. return tfm;
  60. crypto_free_aead(tfm);
  61. return ERR_PTR(err);
  62. }
  63. void ieee80211_aes_gmac_key_free(struct crypto_aead *tfm)
  64. {
  65. crypto_free_aead(tfm);
  66. }