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
10#include <string.h> /* strlen */
11#include <openssl/crypto.h>
12#include "ec_local.h"
13
14static const char *HEX_DIGITS = "0123456789ABCDEF";
15
16/* the return value must be freed (using OPENSSL_free()) */
17char *EC_POINT_point2hex(const EC_GROUP *group,
18                         const EC_POINT *point,
19                         point_conversion_form_t form, BN_CTX *ctx)
20{
21    char *ret, *p;
22    size_t buf_len = 0, i;
23    unsigned char *buf = NULL, *pbuf;
24
25    buf_len = EC_POINT_point2buf(group, point, form, &buf, ctx);
26
27    if (buf_len == 0)
28        return NULL;
29
30    ret = OPENSSL_malloc(buf_len * 2 + 2);
31    if (ret == NULL) {
32        OPENSSL_free(buf);
33        return NULL;
34    }
35    p = ret;
36    pbuf = buf;
37    for (i = buf_len; i > 0; i--) {
38        int v = (int)*(pbuf++);
39        *(p++) = HEX_DIGITS[v >> 4];
40        *(p++) = HEX_DIGITS[v & 0x0F];
41    }
42    *p = '\0';
43
44    OPENSSL_free(buf);
45
46    return ret;
47}
48
49EC_POINT *EC_POINT_hex2point(const EC_GROUP *group,
50                             const char *hex, EC_POINT *point, BN_CTX *ctx)
51{
52    int ok = 0;
53    unsigned char *oct_buf = NULL;
54    size_t len, oct_buf_len = 0;
55    EC_POINT *pt = NULL;
56
57    if (group == NULL || hex == NULL)
58        return NULL;
59
60    if (point == NULL) {
61        pt = EC_POINT_new(group);
62        if (pt == NULL)
63            goto err;
64    } else {
65        pt = point;
66    }
67
68    len = strlen(hex) / 2;
69    oct_buf = OPENSSL_malloc(len);
70    if (oct_buf == NULL)
71        goto err;
72
73    if (!OPENSSL_hexstr2buf_ex(oct_buf, len, &oct_buf_len, hex, '\0')
74        || !EC_POINT_oct2point(group, pt, oct_buf, oct_buf_len, ctx))
75        goto err;
76    ok = 1;
77err:
78    OPENSSL_clear_free(oct_buf, oct_buf_len);
79    if (!ok) {
80        if (pt != point)
81            EC_POINT_clear_free(pt);
82        pt = NULL;
83    }
84    return pt;
85}
86