xref: /optee_os/core/lib/libtomcrypt/src/misc/base16/base16_encode.c (revision 8411e6ad673d20c4742ed30c785e3f5cdea54dfa)
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
6 /**
7    @file base16_encode.c
8    Base16/Hex encode a string, Steffen Jaeckel
9 */
10 
11 #ifdef LTC_BASE16
12 
13 /**
14    Base16 encode a buffer
15    @param in       The input buffer to encode
16    @param inlen    The length of the input buffer
17    @param out      [out] The destination of the Base16 encoded data
18    @param outlen   [in/out] The max size and resulting size of the encoded data
19    @param options  Output 'a-f' on 0 and 'A-F' otherwise.
20    @return CRYPT_OK if successful
21 */
base16_encode(const unsigned char * in,unsigned long inlen,char * out,unsigned long * outlen,unsigned int options)22 int base16_encode(const unsigned char *in,  unsigned long  inlen,
23                                  char *out, unsigned long *outlen,
24                         unsigned int   options)
25 {
26    unsigned long i, x;
27    const char *alphabet;
28    const char *alphabets[2] = {
29       "0123456789abcdef",
30       "0123456789ABCDEF",
31    };
32 
33    LTC_ARGCHK(in     != NULL);
34    LTC_ARGCHK(out    != NULL);
35    LTC_ARGCHK(outlen != NULL);
36 
37    /* check the sizes */
38    x = inlen * 2 + 1;
39 
40    if (x < inlen) return CRYPT_OVERFLOW;
41 
42    if (*outlen < x) {
43       *outlen = x;
44       return CRYPT_BUFFER_OVERFLOW;
45    }
46    x--;
47    *outlen = x; /* returning the length without terminating NUL */
48 
49    if (options == 0) {
50       alphabet = alphabets[0];
51    } else {
52       alphabet = alphabets[1];
53    }
54 
55    for (i = 0; i < x; i += 2) {
56       out[i]   = alphabet[(in[i/2] >> 4) & 0x0f];
57       out[i+1] = alphabet[in[i/2] & 0x0f];
58    }
59    out[x] = '\0';
60 
61    return CRYPT_OK;
62 }
63 
64 #endif
65