]> pd.if.org Git - zpackage/blob - libtomcrypt/src/pk/asn1/der/ia5/der_encode_ia5_string.c
commit files needed for zpm-fetchurl
[zpackage] / libtomcrypt / src / pk / asn1 / der / ia5 / der_encode_ia5_string.c
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2  *
3  * LibTomCrypt is a library that provides various cryptographic
4  * algorithms in a highly modular and flexible manner.
5  *
6  * The library is free for all purposes without any express
7  * guarantee it works.
8  */
9 #include "tomcrypt.h"
10
11 /**
12   @file der_encode_ia5_string.c
13   ASN.1 DER, encode a IA5 STRING, Tom St Denis
14 */
15
16 #ifdef LTC_DER
17
18 /**
19   Store an IA5 STRING
20   @param in       The array of IA5 to store (one per char)
21   @param inlen    The number of IA5 to store
22   @param out      [out] The destination for the DER encoded IA5 STRING
23   @param outlen   [in/out] The max size and resulting size of the DER IA5 STRING
24   @return CRYPT_OK if successful
25 */
26 int der_encode_ia5_string(const unsigned char *in, unsigned long inlen,
27                                 unsigned char *out, unsigned long *outlen)
28 {
29    unsigned long x, y, len;
30    int           err;
31
32    LTC_ARGCHK(in     != NULL);
33    LTC_ARGCHK(out    != NULL);
34    LTC_ARGCHK(outlen != NULL);
35
36    /* get the size */
37    if ((err = der_length_ia5_string(in, inlen, &len)) != CRYPT_OK) {
38       return err;
39    }
40
41    /* too big? */
42    if (len > *outlen) {
43       *outlen = len;
44       return CRYPT_BUFFER_OVERFLOW;
45    }
46
47    /* encode the header+len */
48    x = 0;
49    out[x++] = 0x16;
50    if (inlen < 128) {
51       out[x++] = (unsigned char)inlen;
52    } else if (inlen < 256) {
53       out[x++] = 0x81;
54       out[x++] = (unsigned char)inlen;
55    } else if (inlen < 65536UL) {
56       out[x++] = 0x82;
57       out[x++] = (unsigned char)((inlen>>8)&255);
58       out[x++] = (unsigned char)(inlen&255);
59    } else if (inlen < 16777216UL) {
60       out[x++] = 0x83;
61       out[x++] = (unsigned char)((inlen>>16)&255);
62       out[x++] = (unsigned char)((inlen>>8)&255);
63       out[x++] = (unsigned char)(inlen&255);
64    } else {
65       return CRYPT_INVALID_ARG;
66    }
67
68    /* store octets */
69    for (y = 0; y < inlen; y++) {
70        out[x++] = der_ia5_char_encode(in[y]);
71    }
72
73    /* retun length */
74    *outlen = x;
75
76    return CRYPT_OK;
77 }
78
79 #endif
80
81 /* ref:         $Format:%D$ */
82 /* git commit:  $Format:%H$ */
83 /* commit time: $Format:%ai$ */