ec_print.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <string.h> /* strlen */
  10. #include <openssl/crypto.h>
  11. #include "ec_local.h"
  12. static const char *HEX_DIGITS = "0123456789ABCDEF";
  13. /* the return value must be freed (using OPENSSL_free()) */
  14. char *EC_POINT_point2hex(const EC_GROUP *group,
  15. const EC_POINT *point,
  16. point_conversion_form_t form, BN_CTX *ctx)
  17. {
  18. char *ret, *p;
  19. size_t buf_len = 0, i;
  20. unsigned char *buf = NULL, *pbuf;
  21. buf_len = EC_POINT_point2buf(group, point, form, &buf, ctx);
  22. if (buf_len == 0)
  23. return NULL;
  24. ret = OPENSSL_malloc(buf_len * 2 + 2);
  25. if (ret == NULL) {
  26. OPENSSL_free(buf);
  27. return NULL;
  28. }
  29. p = ret;
  30. pbuf = buf;
  31. for (i = buf_len; i > 0; i--) {
  32. int v = (int)*(pbuf++);
  33. *(p++) = HEX_DIGITS[v >> 4];
  34. *(p++) = HEX_DIGITS[v & 0x0F];
  35. }
  36. *p = '\0';
  37. OPENSSL_free(buf);
  38. return ret;
  39. }
  40. EC_POINT *EC_POINT_hex2point(const EC_GROUP *group,
  41. const char *hex, EC_POINT *point, BN_CTX *ctx)
  42. {
  43. int ok = 0;
  44. unsigned char *oct_buf = NULL;
  45. size_t len, oct_buf_len = 0;
  46. EC_POINT *pt = NULL;
  47. if (group == NULL || hex == NULL)
  48. return NULL;
  49. if (point == NULL) {
  50. pt = EC_POINT_new(group);
  51. if (pt == NULL)
  52. goto err;
  53. } else {
  54. pt = point;
  55. }
  56. len = strlen(hex) / 2;
  57. oct_buf = OPENSSL_malloc(len);
  58. if (oct_buf == NULL)
  59. return NULL;
  60. if (!OPENSSL_hexstr2buf_ex(oct_buf, len, &oct_buf_len, hex, '\0')
  61. || !EC_POINT_oct2point(group, pt, oct_buf, oct_buf_len, ctx))
  62. goto err;
  63. ok = 1;
  64. err:
  65. OPENSSL_clear_free(oct_buf, oct_buf_len);
  66. if (!ok) {
  67. if (pt != point)
  68. EC_POINT_clear_free(pt);
  69. pt = NULL;
  70. }
  71. return pt;
  72. }