1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6   @file der_encode_printable_string.c
7   ASN.1 DER, encode a printable STRING, Tom St Denis
8 */
9 
10 #ifdef LTC_DER
11 
12 /**
13   Store an printable STRING
14   @param in       The array of printable to store (one per char)
15   @param inlen    The number of printable to store
16   @param out      [out] The destination for the DER encoded printable STRING
17   @param outlen   [in/out] The max size and resulting size of the DER printable STRING
18   @return CRYPT_OK if successful
19 */
der_encode_printable_string(const unsigned char * in,unsigned long inlen,unsigned char * out,unsigned long * outlen)20 int der_encode_printable_string(const unsigned char *in, unsigned long inlen,
21                                 unsigned char *out, unsigned long *outlen)
22 {
23    unsigned long x, y, len;
24    int           err;
25 
26    LTC_ARGCHK(in     != NULL);
27    LTC_ARGCHK(out    != NULL);
28    LTC_ARGCHK(outlen != NULL);
29 
30    /* get the size */
31    if ((err = der_length_printable_string(in, inlen, &len)) != CRYPT_OK) {
32       return err;
33    }
34 
35    /* too big? */
36    if (len > *outlen) {
37       *outlen = len;
38       return CRYPT_BUFFER_OVERFLOW;
39    }
40 
41    /* encode the header+len */
42    x = 0;
43    out[x++] = 0x13;
44    len = *outlen - x;
45    if ((err = der_encode_asn1_length(inlen, out + x, &len)) != CRYPT_OK) {
46       return err;
47    }
48    x += len;
49 
50    /* store octets */
51    for (y = 0; y < inlen; y++) {
52        out[x++] = der_printable_char_encode(in[y]);
53    }
54 
55    /* retun length */
56    *outlen = x;
57 
58    return CRYPT_OK;
59 }
60 
61 #endif
62