kdf_util.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
  3. * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
  4. *
  5. * Licensed under the Apache License 2.0 (the "License"). You may not use
  6. * this file except in compliance with the License. You can obtain a copy
  7. * in the file LICENSE in the source distribution or at
  8. * https://www.openssl.org/source/license.html
  9. */
  10. #include <string.h>
  11. #include <stdarg.h>
  12. #include <openssl/kdf.h>
  13. #include <openssl/evp.h>
  14. #include "internal/cryptlib.h"
  15. #include "internal/evp_int.h"
  16. #include "internal/numbers.h"
  17. #include "kdf_local.h"
  18. int call_ctrl(int (*ctrl)(EVP_KDF_IMPL *impl, int cmd, va_list args),
  19. EVP_KDF_IMPL *impl, int cmd, ...)
  20. {
  21. int ret;
  22. va_list args;
  23. va_start(args, cmd);
  24. ret = ctrl(impl, cmd, args);
  25. va_end(args);
  26. return ret;
  27. }
  28. /* Utility functions to send a string or hex string to a ctrl */
  29. int kdf_str2ctrl(EVP_KDF_IMPL *impl,
  30. int (*ctrl)(EVP_KDF_IMPL *impl, int cmd, va_list args),
  31. int cmd, const char *str)
  32. {
  33. return call_ctrl(ctrl, impl, cmd, (const unsigned char *)str, strlen(str));
  34. }
  35. int kdf_hex2ctrl(EVP_KDF_IMPL *impl,
  36. int (*ctrl)(EVP_KDF_IMPL *impl, int cmd, va_list args),
  37. int cmd, const char *hex)
  38. {
  39. unsigned char *bin;
  40. long binlen;
  41. int ret = -1;
  42. bin = OPENSSL_hexstr2buf(hex, &binlen);
  43. if (bin == NULL)
  44. return 0;
  45. if (binlen <= INT_MAX)
  46. ret = call_ctrl(ctrl, impl, cmd, bin, (size_t)binlen);
  47. OPENSSL_free(bin);
  48. return ret;
  49. }
  50. /* Pass a message digest to a ctrl */
  51. int kdf_md2ctrl(EVP_KDF_IMPL *impl,
  52. int (*ctrl)(EVP_KDF_IMPL *impl, int cmd, va_list args),
  53. int cmd, const char *md_name)
  54. {
  55. const EVP_MD *md;
  56. if (md_name == NULL || (md = EVP_get_digestbyname(md_name)) == NULL) {
  57. KDFerr(KDF_F_KDF_MD2CTRL, KDF_R_INVALID_DIGEST);
  58. return 0;
  59. }
  60. return call_ctrl(ctrl, impl, cmd, md);
  61. }