2 * Copyright 2003-2017 The OpenSSL Project Authors. All Rights Reserved.
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
12 #include <openssl/crypto.h>
13 #include "internal/cryptlib.h"
15 char *CRYPTO_strdup(const char *str, const char* file, int line)
21 ret = CRYPTO_malloc(strlen(str) + 1, file, line);
27 char *CRYPTO_strndup(const char *str, size_t s, const char* file, int line)
35 maxlen = OPENSSL_strnlen(str, s);
37 ret = CRYPTO_malloc(maxlen + 1, file, line);
39 memcpy(ret, str, maxlen);
45 void *CRYPTO_memdup(const void *data, size_t siz, const char* file, int line)
49 if (data == NULL || siz >= INT_MAX)
52 ret = CRYPTO_malloc(siz, file, line);
54 CRYPTOerr(CRYPTO_F_CRYPTO_MEMDUP, ERR_R_MALLOC_FAILURE);
57 return memcpy(ret, data, siz);
61 * Give a string of hex digits convert to a buffer
63 unsigned char *OPENSSL_hexstr2buf(const char *str, long *len)
65 unsigned char *hexbuf, *q;
68 const unsigned char *p;
72 if ((hexbuf = OPENSSL_malloc(s >> 1)) == NULL) {
73 CRYPTOerr(CRYPTO_F_OPENSSL_HEXSTR2BUF, ERR_R_MALLOC_FAILURE);
76 for (p = (const unsigned char *)str, q = hexbuf; *p; ) {
82 CRYPTOerr(CRYPTO_F_OPENSSL_HEXSTR2BUF,
83 CRYPTO_R_ODD_NUMBER_OF_DIGITS);
87 cli = OPENSSL_hexchar2int(cl);
88 chi = OPENSSL_hexchar2int(ch);
89 if (cli < 0 || chi < 0) {
91 CRYPTOerr(CRYPTO_F_OPENSSL_HEXSTR2BUF, CRYPTO_R_ILLEGAL_HEX_DIGIT);
94 *q++ = (unsigned char)((chi << 4) | cli);
103 * Given a buffer of length 'len' return a OPENSSL_malloc'ed string with its
104 * hex representation @@@ (Contents of buffer are always kept in ASCII, also
105 * on EBCDIC machines)
107 char *OPENSSL_buf2hexstr(const unsigned char *buffer, long len)
109 static const char hexdig[] = "0123456789ABCDEF";
111 const unsigned char *p;
115 return OPENSSL_zalloc(1);
117 if ((tmp = OPENSSL_malloc(len * 3)) == NULL) {
118 CRYPTOerr(CRYPTO_F_OPENSSL_BUF2HEXSTR, ERR_R_MALLOC_FAILURE);
122 for (i = 0, p = buffer; i < len; i++, p++) {
123 *q++ = hexdig[(*p >> 4) & 0xf];
124 *q++ = hexdig[*p & 0xf];
128 #ifdef CHARSET_EBCDIC
129 ebcdic2ascii(tmp, tmp, q - tmp - 1);