aes_gmac.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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/crypto.h>
  12. #include <linux/err.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[3], ct[1];
  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, 3);
  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. memcpy(iv, nonce, GMAC_NONCE_LEN);
  38. memset(iv + GMAC_NONCE_LEN, 0, sizeof(iv) - GMAC_NONCE_LEN);
  39. iv[AES_BLOCK_SIZE - 1] = 0x01;
  40. sg_init_table(ct, 1);
  41. sg_set_buf(&ct[0], mic, GMAC_MIC_LEN);
  42. aead_request_set_tfm(aead_req, tfm);
  43. aead_request_set_assoc(aead_req, sg, AAD_LEN + data_len);
  44. aead_request_set_crypt(aead_req, NULL, ct, 0, iv);
  45. crypto_aead_encrypt(aead_req);
  46. return 0;
  47. }
  48. struct crypto_aead *ieee80211_aes_gmac_key_setup(const u8 key[],
  49. size_t key_len)
  50. {
  51. struct crypto_aead *tfm;
  52. int err;
  53. tfm = crypto_alloc_aead("gcm(aes)", 0, CRYPTO_ALG_ASYNC);
  54. if (IS_ERR(tfm))
  55. return tfm;
  56. err = crypto_aead_setkey(tfm, key, key_len);
  57. if (!err)
  58. err = crypto_aead_setauthsize(tfm, GMAC_MIC_LEN);
  59. if (!err)
  60. return tfm;
  61. crypto_free_aead(tfm);
  62. return ERR_PTR(err);
  63. }
  64. void ieee80211_aes_gmac_key_free(struct crypto_aead *tfm)
  65. {
  66. crypto_free_aead(tfm);
  67. }