mbedtls_adapter.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* This file is part of Graphene Library OS.
  2. Graphene Library OS is free software: you can redistribute it and/or
  3. modify it under the terms of the GNU General Public License
  4. as published by the Free Software Foundation, either version 3 of the
  5. License, or (at your option) any later version.
  6. Graphene Library OS is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License
  11. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  12. #include <stdint.h>
  13. #include "pal.h"
  14. #include "pal_crypto.h"
  15. #include "pal_error.h"
  16. #include "crypto/mbedtls/mbedtls/cmac.h"
  17. #include "crypto/mbedtls/mbedtls/sha256.h"
  18. #define BITS_PER_BYTE 8
  19. int lib_SHA256Init(LIB_SHA256_CONTEXT *context)
  20. {
  21. mbedtls_sha256_init(context);
  22. mbedtls_sha256_starts(context, 0 /* 0 = use SSH256 */);
  23. return 0;
  24. }
  25. int lib_SHA256Update(LIB_SHA256_CONTEXT *context, const uint8_t *data,
  26. uint64_t len)
  27. {
  28. /* For compatibility with other SHA256 providers, don't support
  29. * large lengths. */
  30. if (len > UINT32_MAX) {
  31. return -PAL_ERROR_INVAL;
  32. }
  33. mbedtls_sha256_update(context, data, len);
  34. return 0;
  35. }
  36. int lib_SHA256Final(LIB_SHA256_CONTEXT *context, uint8_t *output)
  37. {
  38. mbedtls_sha256_finish(context, output);
  39. /* This function is called free, but it doesn't actually free the memory.
  40. * It zeroes out the context to avoid potentially leaking information
  41. * about the hash that was just performed. */
  42. mbedtls_sha256_free(context);
  43. return 0;
  44. }
  45. int lib_AESCMAC(const uint8_t *key, uint64_t key_len, const uint8_t *input,
  46. uint64_t input_len, uint8_t *mac, uint64_t mac_len) {
  47. mbedtls_cipher_type_t cipher;
  48. switch (key_len) {
  49. case 16:
  50. cipher = MBEDTLS_CIPHER_AES_128_ECB;
  51. break;
  52. case 24:
  53. cipher = MBEDTLS_CIPHER_AES_192_ECB;
  54. break;
  55. case 32:
  56. cipher = MBEDTLS_CIPHER_AES_256_ECB;
  57. break;
  58. default:
  59. return -PAL_ERROR_INVAL;
  60. }
  61. const mbedtls_cipher_info_t *cipher_info =
  62. mbedtls_cipher_info_from_type(cipher);
  63. if (mac_len < cipher_info->block_size) {
  64. return -PAL_ERROR_INVAL;
  65. }
  66. return mbedtls_cipher_cmac(cipher_info,
  67. key, key_len * BITS_PER_BYTE,
  68. input, input_len, mac);
  69. }