Skip to content

Commit

Permalink
Add OPENSSL_hexstr2buf
Browse files Browse the repository at this point in the history
  • Loading branch information
justsmth committed Sep 10, 2024
1 parent 9f23548 commit 01cd58c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
32 changes: 32 additions & 0 deletions crypto/mem.c
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,38 @@ int OPENSSL_fromxdigit(uint8_t *out, int c) {
return 0;
}

uint8_t *OPENSSL_hexstr2buf(const char *str, long *len) {
if (str == NULL) {
return NULL;
}

const size_t slen = strlen(str);
if (slen % 2 != 0) {
return NULL;
}

const size_t buflen = slen / 2;
uint8_t *buf = OPENSSL_zalloc(buflen);
if (buf == NULL) {
return NULL;
}

for (size_t i = 0; i < buflen; i++) {
uint8_t hi, lo;
if (!OPENSSL_fromxdigit(&hi, str[2 * i]) ||
!OPENSSL_fromxdigit(&lo, str[2 * i + 1])) {
OPENSSL_free(buf);
return NULL;
}
buf[i] = (hi << 4) | lo;
}

if (len != NULL) {
*len = buflen;
}
return buf;
}

int OPENSSL_isalnum(int c) { return OPENSSL_isalpha(c) || OPENSSL_isdigit(c); }

int OPENSSL_tolower(int c) {
Expand Down
7 changes: 7 additions & 0 deletions include/openssl/mem.h
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,13 @@ OPENSSL_EXPORT int OPENSSL_isxdigit(int c);
// zero is returned.
OPENSSL_EXPORT int OPENSSL_fromxdigit(uint8_t *out, int c);

// OPENSSL_hexstr2buf allocates and returns a buffer containing the bytes
// represented by the hexadecimal string |str|. |str| must be a NULL terminated
// string of hex characters. The length of the buffer is stored in |*len|.
// |len| must not be NULL. The caller must free the returned
// buffer with |OPENSSL_free|. If |str| is malformed, NULL is returned.
OPENSSL_EXPORT uint8_t *OPENSSL_hexstr2buf(const char *str, long *len);

// OPENSSL_isalnum is a locale-independent, ASCII-only version of isalnum(3), It
// only recognizes what |OPENSSL_isalpha| and |OPENSSL_isdigit| recognize.
OPENSSL_EXPORT int OPENSSL_isalnum(int c);
Expand Down

0 comments on commit 01cd58c

Please sign in to comment.