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 #include "tomcrypt_private.h"
11 
12 /**
13    @file radix_to_bin.c
14    Convert data from a specific radix to binary.
15    Steffen Jaeckel
16 */
17 
18 /**
19    Convert data from a specific radix to binary
20 
21       The default MPI descriptors #ltm_desc, #tfm_desc and #gmp_desc
22       have the following restrictions on parameters:
23 
24         \p in    - NUL-terminated char buffer
25 
26         \p radix - 2..64
27 
28    @param in    The input
29    @param radix The radix of the input
30    @param out   The output buffer
31    @param len   [in/out] The length of the output buffer
32 
33    @return CRYPT_OK on success.
34 */
radix_to_bin(const void * in,int radix,void * out,unsigned long * len)35 int radix_to_bin(const void *in, int radix, void *out, unsigned long *len)
36 {
37    unsigned long l;
38    void* mpi;
39    int err;
40 
41    LTC_ARGCHK(in  != NULL);
42    LTC_ARGCHK(len != NULL);
43 
44    if ((err = mp_init(&mpi)) != CRYPT_OK) return err;
45    if ((err = mp_read_radix(mpi, in, radix)) != CRYPT_OK) goto LBL_ERR;
46 
47    if ((l = mp_unsigned_bin_size(mpi)) > *len) {
48       *len = l;
49       err = CRYPT_BUFFER_OVERFLOW;
50       goto LBL_ERR;
51    }
52    *len = l;
53 
54    if ((err = mp_to_unsigned_bin(mpi, out)) != CRYPT_OK) goto LBL_ERR;
55 
56 LBL_ERR:
57    mp_clear(mpi);
58    return err;
59 }
60 
61 /* ref:         $Format:%D$ */
62 /* git commit:  $Format:%H$ */
63 /* commit time: $Format:%ai$ */
64