1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6    @file radix_to_bin.c
7    Convert data from a specific radix to binary.
8    Steffen Jaeckel
9 */
10 
11 /**
12    Convert data from a specific radix to binary
13 
14       The default MPI descriptors #ltm_desc, #tfm_desc and #gmp_desc
15       have the following restrictions on parameters:
16 
17         \p in    - NUL-terminated char buffer
18 
19         \p radix - 2..64
20 
21    @param in    The input
22    @param radix The radix of the input
23    @param out   The output buffer
24    @param len   [in/out] The length of the output buffer
25 
26    @return CRYPT_OK on success.
27 */
radix_to_bin(const void * in,int radix,void * out,unsigned long * len)28 int radix_to_bin(const void *in, int radix, void *out, unsigned long *len)
29 {
30    unsigned long l;
31    void* mpi;
32    int err;
33 
34    LTC_ARGCHK(in  != NULL);
35    LTC_ARGCHK(len != NULL);
36 
37    if ((err = mp_init(&mpi)) != CRYPT_OK) return err;
38    if ((err = mp_read_radix(mpi, in, radix)) != CRYPT_OK) goto LBL_ERR;
39 
40    if ((l = mp_unsigned_bin_size(mpi)) > *len) {
41       *len = l;
42       err = CRYPT_BUFFER_OVERFLOW;
43       goto LBL_ERR;
44    }
45    *len = l;
46 
47    if ((err = mp_to_unsigned_bin(mpi, out)) != CRYPT_OK) goto LBL_ERR;
48 
49 LBL_ERR:
50    mp_clear(mpi);
51    return err;
52 }
53