1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 *
4 * LibTomCrypt is a library that provides various cryptographic
5 * algorithms in a highly modular and flexible manner.
6 *
7 * The library is free for all purposes without any express
8 * guarantee it works.
9 */
10
11 #include "tomcrypt_private.h"
12
13 /**
14 @file base16_encode.c
15 Base16/Hex encode a string, Steffen Jaeckel
16 */
17
18 #ifdef LTC_BASE16
19
20 /**
21 Base16 encode a buffer
22 @param in The input buffer to encode
23 @param inlen The length of the input buffer
24 @param out [out] The destination of the Base16 encoded data
25 @param outlen [in/out] The max size and resulting size of the encoded data
26 @param options Output 'a-f' on 0 and 'A-F' otherwise.
27 @return CRYPT_OK if successful
28 */
base16_encode(const unsigned char * in,unsigned long inlen,char * out,unsigned long * outlen,unsigned int options)29 int base16_encode(const unsigned char *in, unsigned long inlen,
30 char *out, unsigned long *outlen,
31 unsigned int options)
32 {
33 unsigned long i, x;
34 const char *alphabet;
35 const char *alphabets[2] = {
36 "0123456789abcdef",
37 "0123456789ABCDEF",
38 };
39
40 LTC_ARGCHK(in != NULL);
41 LTC_ARGCHK(out != NULL);
42 LTC_ARGCHK(outlen != NULL);
43
44 /* check the sizes */
45 x = inlen * 2 + 1;
46
47 if (x < inlen) return CRYPT_OVERFLOW;
48
49 if (*outlen < x) {
50 *outlen = x;
51 return CRYPT_BUFFER_OVERFLOW;
52 }
53 x--;
54 *outlen = x; /* returning the length without terminating NUL */
55
56 if (options == 0) {
57 alphabet = alphabets[0];
58 } else {
59 alphabet = alphabets[1];
60 }
61
62 for (i = 0; i < x; i += 2) {
63 out[i] = alphabet[(in[i/2] >> 4) & 0x0f];
64 out[i+1] = alphabet[in[i/2] & 0x0f];
65 }
66 out[x] = '\0';
67
68 return CRYPT_OK;
69 }
70
71 #endif
72
73 /* ref: $Format:%D$ */
74 /* git commit: $Format:%H$ */
75 /* commit time: $Format:%ai$ */
76